cucumber.api.java.en.When Java Examples

The following examples show how to use cucumber.api.java.en.When. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StepDefs.java    From galeb with Apache License 2.0 6 votes vote down vote up
@When("^request json body has:$")
public void requestJsonBodyHas(Map<String, String> jsonComponents) throws Throwable {
    if (!jsonComponents.isEmpty() && !jsonComponents.keySet().contains("")) {
        final Map<String, Object> jsonComponentsProcessed = new HashMap<>();
        jsonComponents.entrySet().stream().forEach(entry -> {
            String oldValue = entry.getValue();
            if (oldValue.contains("[")) {
                String[] arrayOfValues = oldValue.replaceAll("\\[|\\]| ", "").split(",");
                for (int x = 0; x < arrayOfValues.length; x++) {
                    arrayOfValues[x] = processFullUrl(arrayOfValues[x]);
                }
                jsonComponentsProcessed.put(entry.getKey(), arrayOfValues);
            } else {
                oldValue = processFullUrl(oldValue);
                jsonComponentsProcessed.put(entry.getKey(), oldValue);
            }
        });
        String json = jsonParser.toJson(jsonComponentsProcessed);
        request.body(json);
    }
}
 
Example #2
Source File: JPAStepsDef.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@When("^I update this Encounter$")
public void i_update_this_Encounter() throws Throwable {


    InputStream inputStream =
            Thread.currentThread().getContextClassLoader().getResourceAsStream("json/EncounterExampleTwo.json");
    assertNotNull(inputStream);
    Reader reader = new InputStreamReader(inputStream);

    Encounter encounter = ctx.newJsonParser().parseResource(Encounter.class, reader);
    try {
        encounter = encounterRepository.create(ctx,encounter,null,"Encounter?identifier=" + encounter.getIdentifier().get(0).getSystem() + "%7C" +encounter.getIdentifier().get(0).getValue());
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}
 
Example #3
Source File: ExistingCustomerBooksRoom.java    From Spring with Apache License 2.0 6 votes vote down vote up
@When("^The user books room (\\d+) for (\\d+) nights$")
public void the_user_books_room_for_nights(int arg1, int arg2) {
	theRoom = rest.getForObject("http://localhost:8082/rooms/search/byRoomNumber?roomNumber=" + arg1, Room.class);

	final Booking booking = new Booking();
	booking.setCustomerId(joeUser.getId());
	booking.setRoomNumber(theRoom.getRoomNumber());

	final Date startDate = new Date(System.currentTimeMillis());
	final Calendar endDate = new GregorianCalendar();
	endDate.add(Calendar.DAY_OF_YEAR, 5);

	booking.setStartDate(startDate);
	booking.setEndDate(endDate.getTime());

	final ResponseEntity response = rest.postForEntity("http://localhost:8083/bookings", booking, null);

	assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.CREATED);
	bookingLocation = response.getHeaders().get("Location").get(0);
	assertThat(bookingLocation).startsWith("bookings/");
}
 
Example #4
Source File: JPAStepsDef.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@When("^I update this Procedure$")
public void i_update_this_Procedure() throws Throwable {
    InputStream inputStream =
            Thread.currentThread().getContextClassLoader().getResourceAsStream("json/ProcedureExampleTwo.json");
    assertNotNull(inputStream);
    Reader reader = new InputStreamReader(inputStream);

    Procedure procedure = ctx.newJsonParser().parseResource(Procedure.class, reader);
    try {
        procedure = procedureRepository.create(ctx,procedure,null,"Procedure?identifier=" + procedure.getIdentifier().get(0).getSystem() + "%7C" +procedure.getIdentifier().get(0).getValue());
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}
 
Example #5
Source File: InputInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Ввод в поле случайного дробного числа в заданном диапазоне и формате с последующим сохранением этого значения в переменную
 * Пример формата ввода: ###.##
 */
@Когда("^в поле \"([^\"]*)\" введено случайное дробное число от (\\d+) до (\\d+) в формате \"([^\"]*)\" и сохранено в переменную \"([^\"]*)\"$")
@When("^into the field named \"([^\"]*)\" has been entered random fractional number from (\\d+) to (\\d+) in format \"([^\"]*)\" and saved to variable named \"([^\"]*)\"$")
public void setRandomNumSequenceWithIntAndFract(String fieldName, double valueFrom, double valueTo, String outputFormat, String saveToVariableName) {
    outputFormat = outputFormat.replaceAll("#", "0");
    double finalValue = ThreadLocalRandom.current().nextDouble(valueFrom, valueTo);
    setFieldValue(fieldName, new DecimalFormat(outputFormat).format(finalValue));
    akitaScenario.setVar(saveToVariableName, new DecimalFormat(outputFormat).format(finalValue));
    akitaScenario.write(String.format("В поле [%s] введено значение [%s] и сохранено в переменную [%s]",
            fieldName, new DecimalFormat(outputFormat).format(finalValue), saveToVariableName));
}
 
Example #6
Source File: JPAStepsDef.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@When("^I update this AllergyIntolerance$")
public void i_update_this_AllergyIntolerance() throws Throwable {
    InputStream inputStream =
            Thread.currentThread().getContextClassLoader().getResourceAsStream("json/AllergyIntoleranceExampleTwo.json");
    assertNotNull(inputStream);
    Reader reader = new InputStreamReader(inputStream);

    AllergyIntolerance allergy = ctx.newJsonParser().parseResource(AllergyIntolerance.class, reader);
    try {
        allergy = allergyIntoleranceRepository.create(ctx,allergy,null,"AllergyIntolerance?identifier=" + allergy.getIdentifier().get(0).getSystem() + "%7C" +allergy.getIdentifier().get(0).getValue());
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}
 
Example #7
Source File: DatabaseSteps.java    From pandaria with MIT License 5 votes vote down vote up
@When("^query:$")
public void query(String sql) {
    databaseQueryContext.dataSource(dataSources.dataSource(DEFAULT));
    databaseQueryContext.query(expressions.evaluate(sql));
    databaseQueryContext.send();
    verifier.toBeVerified(databaseQueryContext.results());
    wait.waitable(databaseQueryContext);
}
 
Example #8
Source File: StepDefs.java    From galeb with Apache License 2.0 5 votes vote down vote up
@When("^request uri-list body has:$")
public void requestUriListBodyHas(List<String> uriList) {
    request.contentType("text/uri-list");
    if (!uriList.isEmpty()) {
        String body = uriList.stream().map(this::processFullUrl)
                .collect(Collectors.joining("\n"));
        request.body(body);
    }
}
 
Example #9
Source File: ElementsInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Выполняется наведение курсора на элемент
 */
@Когда("^выполнен ховер на (?:поле|элемент) \"([^\"]*)\"$")
@When("^hovered (?:field|element) named \"([^\"]*)\"$")
public void elementHover(String elementName) {
    SelenideElement field = akitaScenario.getCurrentPage().getElement(elementName);
    field.hover();
}
 
Example #10
Source File: ElementsInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
* Выполняется нажатие на кнопку и подгружается указанный файл
* Селектор кнопки должны быть строго на input элемента
* Можно указать путь до файла. Например, src/test/resources/example.pdf
*/
@Когда("^выполнено нажатие на кнопку \"([^\"]*)\" и загружен файл \"([^\"]*)\"$")
@When("^clicked on button named \"([^\"]*)\" and file named \"([^\"]*)\" has been loaded$")
public void clickOnButtonAndUploadFile(String buttonName, String fileName) {
    String file = loadValueFromFileOrPropertyOrVariableOrDefault(fileName);
    File attachmentFile = new File(file);
    akitaScenario.getCurrentPage().getElement(buttonName).uploadFile(attachmentFile);
}
 
Example #11
Source File: DatabaseSteps.java    From pandaria with MIT License 5 votes vote down vote up
@When("^query: ([^\"]*)$")
public void queryFromFile(String fileName) throws IOException {
    String file = configuration.classpathFile(fileName);
    databaseQueryContext.dataSource(dataSources.dataSource(DEFAULT));
    databaseQueryContext.query(expressions.evaluate(read(file)));
    databaseQueryContext.send();
    verifier.toBeVerified(databaseQueryContext.results());
    wait.waitable(databaseQueryContext);
}
 
Example #12
Source File: HandleResourceRunSteps.java    From jwala with Apache License 2.0 5 votes vote down vote up
@When("^I add property \"(.*)\"$")
public void addProperty(String property) {
    jwalaUi.waitUntilElementIsNotVisible(
            By.xpath("//div[text()='Please select a JVM, Web Server or Web Application and a resource']"), 5);
    jwalaUi.click(By.xpath("//div[@class='CodeMirror-lines']"));
    jwalaUi.sendKeysViaActions("\n" + property + "\n");
}
 
Example #13
Source File: DatabaseSteps.java    From pandaria with MIT License 5 votes vote down vote up
@When("^db: ([^\" ]*) query:$")
public void queryByDb(String dbName, String sql) {
    databaseQueryContext.dataSource(dataSources.dataSource(dbName));
    databaseQueryContext.query(expressions.evaluate(sql));
    databaseQueryContext.send();
    verifier.toBeVerified(databaseQueryContext.results());
    wait.waitable(databaseQueryContext);
}
 
Example #14
Source File: DatabaseSteps.java    From pandaria with MIT License 5 votes vote down vote up
@When("^db: ([^\" ]*) query: ([^\"]*)$")
public void queryFromFileByDb(String dbName, String fileName) throws IOException {
    String file = configuration.classpathFile(fileName);
    databaseQueryContext.dataSource(dataSources.dataSource(dbName));
    databaseQueryContext.query(expressions.evaluate(read(file)));
    databaseQueryContext.send();
    verifier.toBeVerified(databaseQueryContext.results());
    wait.waitable(databaseQueryContext);
}
 
Example #15
Source File: RoundUpSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Выполняется запуск js-скрипта с указанием в js.executeScript его логики
 * Скрипт можно передать как аргумент метода или значение из application.properties
 */
@Когда("^выполнен js-скрипт \"([^\"]*)\"")
@When("^executed js-script \"([^\"]*)\"$")
public void executeJsScript(String scriptName) {
    String content = loadValueFromFileOrPropertyOrVariableOrDefault(scriptName);
    Selenide.executeJavaScript(content);
}
 
Example #16
Source File: WebPageInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Выполняется переход по заданной ссылке,
 * ссылка берется из property / переменной, если такая переменная не найдена,
 * то берется переданное значение
 * при этом все ключи переменных в фигурных скобках
 * меняются на их значения из хранилища akitaScenario
 */
@Когда("^совершен переход по ссылке \"([^\"]*)\"$")
@When("^URL\"([^\"]*)\" has been opened$")
public void goToUrl(String address) {
    String url = resolveVars(getPropertyOrStringVariableOrValue(address));
    open(url);
    akitaScenario.write("Url = " + url);
}
 
Example #17
Source File: iOSPageSteps.java    From Mobile-Test-Automation-with-Appium with MIT License 5 votes vote down vote up
@When("^I launch iOS app$")
public void iLaunchIOSApp() throws Throwable {
    /*
        Moved the Desired Capability code to Starting steps to have that at one place
        This method can be changed to do some assertion as shown below
    */
    Assert.assertTrue(appiumDriver.findElementByAccessibilityId("TextField1").isDisplayed());
}
 
Example #18
Source File: StepDefinitions.java    From demo-java with MIT License 5 votes vote down vote up
@When("^I add (\\d+) items? to the cart$")
public void add_items_to_cart(int items){
    By itemButton = By.className("btn_primary");

    IntStream.range(0, items).forEach(i -> {
        wait.until(ExpectedConditions.elementToBeClickable(getDriver().findElement(itemButton)));
        getDriver().findElement(itemButton).click();
    });
}
 
Example #19
Source File: InputInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Ввод в поле случайной последовательности латинских или кириллических букв задаваемой длины
 */
@Когда("^в поле \"([^\"]*)\" введено (\\d+) случайных символов на (кириллице|латинице)$")
@When("^into the field named \"([^\"]*)\" has been entered (\\d+) random (?:latin|cyrillic) symbol(|s)$")
public void setRandomCharSequence(String elementName, int seqLength, String lang) {
    SelenideElement valueInput = akitaScenario.getCurrentPage().getElement(elementName);
    cleanField(elementName);

    if (lang.equals("кириллице")) lang = "ru";
    else lang = "en";
    String charSeq = getRandCharSequence(seqLength, lang);
    valueInput.setValue(charSeq);
    akitaScenario.write("Строка случайных символов равна :" + charSeq);
}
 
Example #20
Source File: InputInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Добавление строки (в приоритете: из property, из переменной сценария, значение аргумента) в поле к уже заполненой строке
 */
@Когда("^в элемент \"([^\"]*)\" дописывается значение \"(.*)\"$")
@When("^element named \"([^\"]*)\" has been suplemented with value of \"(.*)\"$")
public void addValue(String elementName, String value) {
    value = getPropertyOrStringVariableOrValue(value);
    SelenideElement field = akitaScenario.getCurrentPage().getElement(elementName);
    String oldValue = field.getValue();
    if (oldValue.isEmpty()) {
        oldValue = field.getText();
    }
    field.setValue("");
    field.setValue(oldValue + value);
}
 
Example #21
Source File: BuyingAndSellingSharesStepDefinitions.java    From bdd-trader with Apache License 2.0 5 votes vote down vote up
@When("^(.*) (?:purchases|has purchased) (\\d+) (.*) shares at \\$(.*) each$")
public void purchases_shares(String traderName, int amount, String securityCode, double marketPrice) {

    Actor trader = OnStage.theActorCalled(traderName);

    Client registeredClient = trader.recall("registeredClient");

    trader.attemptsTo(
            PlaceOrder.to(Buy, amount)
                      .sharesOf(securityCode)
                      .atPriceOf(marketPrice)
                      .forClient(registeredClient)
    );
}
 
Example #22
Source File: ListInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Выбор из списка со страницы элемента, который содержит заданный текст
 * (в приоритете: из property, из переменной сценария, значение аргумента)
 * Не чувствителен к регистру
 */
@Когда("^в списке \"([^\"]*)\" выбран элемент содержащий текст \"([^\"]*)\"$")
@When("^selected element from the \"([^\"]*)\" list that contains text \"([^\"]*)\"$")
public void selectElementInListIfFoundByText(String listName, String expectedValue) {
    final String value = getPropertyOrStringVariableOrValue(expectedValue);
    List<SelenideElement> listOfElementsFromPage = akitaScenario.getCurrentPage().getElementsList(listName);
    List<String> elementsListText = listOfElementsFromPage.stream()
        .map(element -> element.getText().trim().toLowerCase())
        .collect(toList());
    listOfElementsFromPage.stream()
        .filter(element -> element.getText().trim().toLowerCase().contains(value.toLowerCase()))
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException(String.format("Элемент [%s] не найден в списке %s: [%s] ", value, listName, elementsListText)))
        .click();
}
 
Example #23
Source File: InputInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Ввод в поле случайной последовательности цифр задаваемой длины
 */
@Когда("^в поле \"([^\"]*)\" введено случайное число из (\\d+) (?:цифр|цифры)$")
@When("^into the field named \"([^\"]*)\" has been entered (\\d+) random digit(|s)$")
public void inputRandomNumSequence(String elementName, int seqLength) {
    SelenideElement valueInput = akitaScenario.getCurrentPage().getElement(elementName);
    cleanField(elementName);
    String numSeq = RandomStringUtils.randomNumeric(seqLength);
    valueInput.setValue(numSeq);
    akitaScenario.write(String.format("В поле [%s] введено значение [%s]", elementName, numSeq));
}
 
Example #24
Source File: JPAStepsDef.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
@When("^I update this Immunisation$")
public void i_update_this_Immunisation() throws Throwable {
    InputStream inputStream =
            Thread.currentThread().getContextClassLoader().getResourceAsStream("json/ImmunisationExampleTwo.json");
    assertNotNull(inputStream);
    Reader reader = new InputStreamReader(inputStream);

    Immunization immunization = ctx.newJsonParser().parseResource(Immunization.class, reader);
    try {
        immunization = immunizationRepository.create(ctx,immunization,null,"Immunization?identifier=" + immunization.getIdentifier().get(0).getSystem() + "%7C" +immunization.getIdentifier().get(0).getValue());
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}
 
Example #25
Source File: InputInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Ввод в поле случайной последовательности цифр задаваемой длины и сохранение этого значения в переменную
 */
@Когда("^в поле \"([^\"]*)\" введено случайное число из (\\d+) (?:цифр|цифры) и сохранено в переменную \"([^\"]*)\"$")
@When("^into the field named \"([^\"]*)\" has been entered (\\d+) random digit(|s) and saved to variable named \"([^\"]*)\"$")
public void inputAndSetRandomNumSequence(String elementName, int seqLength, String varName) {
    SelenideElement valueInput = akitaScenario.getCurrentPage().getElement(elementName);
    cleanField(elementName);
    String numSeq = RandomStringUtils.randomNumeric(seqLength);
    valueInput.setValue(numSeq);
    akitaScenario.setVar(varName, numSeq);
    akitaScenario.write(String.format("В поле [%s] введено значение [%s] и сохранено в переменную [%s]",
            elementName, numSeq, varName));
}
 
Example #26
Source File: StepActions.java    From karate with MIT License 4 votes vote down vote up
@Override
@When("^header ([^\\s]+) = (.+)")
public void header(String name, List<String> values) {
    context.header(name, values);
}
 
Example #27
Source File: JvmControlRunSteps.java    From jwala with Apache License 2.0 4 votes vote down vote up
@When("^I click the operation's confirm delete JVM dialog yes button$")
public void clickConfirmJvmDeleteYesButton() {
    jwalaUi.clickYes();
}
 
Example #28
Source File: CucumberTestSteps.java    From Cloud-Native-Applications-in-Java with MIT License 4 votes vote down vote up
@When("^get (.*) Service is called with a non existing product id (\\d+)$")
public void get_Product_Service_is_called_with_a_non_existing_product_id(String serviceName, int prodId) throws Throwable {
	errResponse = this.restTemplate.getForEntity("/"+serviceName+"/" + prodId, String.class, new HashMap<>());
}
 
Example #29
Source File: BookSearchSteps.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 4 votes vote down vote up
@When("^the customer searches for books published between (\\d+) and (\\d+)$")
public void setSearchParameters(@Format("yyyy") Date from,
        @Format("yyyy") Date to) {
    result = library.findBooks(from, to);
}
 
Example #30
Source File: HandleResourceRunSteps.java    From jwala with Apache License 2.0 4 votes vote down vote up
@When("^I click \"(.*)\" component$")
public void selectComponent(String component) {
    jwalaUi.clickWhenReady(By.xpath("//span[contains(text(),'" + component + "')]"));
}