类cucumber.api.java.en.When源码实例Demo

下面列出了怎么用cucumber.api.java.en.When的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Spring   文件: ExistingCustomerBooksRoom.java
@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/");
}
 
@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());
    }
}
 
源代码3 项目: galeb   文件: StepDefs.java
@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);
    }
}
 
源代码4 项目: akita   文件: InputInteractionSteps.java
/**
 * Ввод в поле случайного дробного числа в заданном диапазоне и формате с последующим сохранением этого значения в переменную
 * Пример формата ввода: ###.##
 */
@Когда("^в поле \"([^\"]*)\" введено случайное дробное число от (\\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));
}
 
源代码5 项目: akita   文件: ElementsInteractionSteps.java
/**
* Выполняется нажатие на кнопку и подгружается указанный файл
* Селектор кнопки должны быть строго на 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);
}
 
@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());
}
 
@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)
    );
}
 
源代码8 项目: akita   文件: ListInteractionSteps.java
/**
 * Выбор из списка со страницы элемента, который содержит заданный текст
 * (в приоритете: из 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();
}
 
源代码9 项目: akita   文件: InputInteractionSteps.java
/**
 * Ввод в поле случайной последовательности цифр задаваемой длины
 */
@Когда("^в поле \"([^\"]*)\" введено случайное число из (\\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));
}
 
@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());
    }
}
 
源代码11 项目: akita   文件: InputInteractionSteps.java
/**
 * Ввод в поле случайной последовательности цифр задаваемой длины и сохранение этого значения в переменную
 */
@Когда("^в поле \"([^\"]*)\" введено случайное число из (\\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));
}
 
源代码12 项目: demo-java   文件: StepDefinitions.java
@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();
    });
}
 
源代码13 项目: akita   文件: ElementsInteractionSteps.java
/**
 * Выполняется наведение курсора на элемент
 */
@Когда("^выполнен ховер на (?:поле|элемент) \"([^\"]*)\"$")
@When("^hovered (?:field|element) named \"([^\"]*)\"$")
public void elementHover(String elementName) {
    SelenideElement field = akitaScenario.getCurrentPage().getElement(elementName);
    field.hover();
}
 
源代码14 项目: akita   文件: RoundUpSteps.java
/**
 * Выполняется запуск js-скрипта с указанием в js.executeScript его логики
 * Скрипт можно передать как аргумент метода или значение из application.properties
 */
@Когда("^выполнен js-скрипт \"([^\"]*)\"")
@When("^executed js-script \"([^\"]*)\"$")
public void executeJsScript(String scriptName) {
    String content = loadValueFromFileOrPropertyOrVariableOrDefault(scriptName);
    Selenide.executeJavaScript(content);
}
 
源代码15 项目: pandaria   文件: DatabaseSteps.java
@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);
}
 
源代码16 项目: pandaria   文件: DatabaseSteps.java
@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);
}
 
源代码17 项目: pandaria   文件: DatabaseSteps.java
@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);
}
 
源代码18 项目: pandaria   文件: DatabaseSteps.java
@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);
}
 
@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());
    }
}
 
源代码20 项目: akita   文件: WebPageInteractionSteps.java
/**
 * Выполняется переход по заданной ссылке,
 * ссылка берется из property / переменной, если такая переменная не найдена,
 * то берется переданное значение
 * при этом все ключи переменных в фигурных скобках
 * меняются на их значения из хранилища akitaScenario
 */
@Когда("^совершен переход по ссылке \"([^\"]*)\"$")
@When("^URL\"([^\"]*)\" has been opened$")
public void goToUrl(String address) {
    String url = resolveVars(getPropertyOrStringVariableOrValue(address));
    open(url);
    akitaScenario.write("Url = " + url);
}
 
源代码21 项目: akita   文件: InputInteractionSteps.java
/**
 * Добавление строки (в приоритете: из 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);
}
 
源代码22 项目: akita   文件: InputInteractionSteps.java
/**
 * Ввод в поле случайной последовательности латинских или кириллических букв задаваемой длины
 */
@Когда("^в поле \"([^\"]*)\" введено (\\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);
}
 
@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());
    }
}
 
源代码24 项目: galeb   文件: StepDefs.java
@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);
    }
}
 
源代码25 项目: jwala   文件: HandleResourceRunSteps.java
@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");
}
 
@When("^the calculator sums them$")
public void the_calculator_sums_them() throws Throwable {
    String url = String.format("%s/sum?a=%s&b=%s", server, a, b);
    result = restTemplate.getForObject(url, String.class);
}
 
@When("^the calculator sums them$")
public void the_calculator_sums_them() throws Throwable {
    String url = String.format("%s/sum?a=%s&b=%s", server, a, b);
    result = restTemplate.getForObject(url, String.class);
}
 
源代码28 项目: jwala   文件: UploadResourceRunSteps.java
@When("^I click the add resource button$")
public void clickAddResourceBtn() {
    jwalaUi.clickWhenReady(By.xpath("//span[contains(@class, 'ui-icon-plusthick')]"));
}
 
源代码29 项目: jwala   文件: ManageDrainRunSteps.java
@When("^I click on the drain button for all webservers in the group$")
public void clickGroupDrainForWebServers() {
    jwalaUi.clickWhenReady(By.xpath("//button[span[text()='Drain Web Servers']]"));
}
 
@When("^the calculator sums them$")
public void the_calculator_sums_them() throws Throwable {
    String url = String.format("%s/sum?a=%s&b=%s", server, a, b);
    result = restTemplate.getForObject(url, String.class);
}