bdd cucumber tutorial with examples
이 심층적 인 Cucumber 자습서에서는 BDD 및 그 이점, Cucumber 프레임 워크, 환경 설정, 테스트 스크립트 생성, Cucumber 기능, 보고서 등에 대해 설명합니다.
오이는 매우 인기를 얻었으며 현재 소프트웨어 테스팅 산업에서 널리 사용되고 있습니다.
전제 조건 – 대상 수신자는 Scrum, Maven, TestNG 등에 대한 지식이 있어야합니다.
학습 내용 :
- BDD의 배경
- 행동 기반 개발 (BDD)의 이점
- BDD 도구
- 왜 오이?
- 오이는 어떻게 작동합니까?
- 환경 설정
- 오이를 사용하여 테스트 케이스 작성
- 오 이용 파일 생성
- 오이 특징
- 오이로 TestNG
- 결론
- 추천 도서
BDD의 배경
TDD Framework of Agile 방법론에서는 일반적으로 테스트 케이스를 먼저 작성한 다음 실행합니다. 이는 테스트 커버리지를 획득하고 빌드가 프로덕션 준비가되었는지 확인하는 데 유용합니다.
그러나 테스트에 Behaviors, Features 등을 도입하여 TDD 프레임 워크를 강화한 다음이를 실행할 수 있습니다. TDD에 대한 이러한 향상된 기능을 BDD (Behavior Driven Development)라고합니다.
행동 기반 개발 (BDD)의 이점
BDD 사용의 몇 가지 이점은 다음과 같습니다.
#1) 공통 플랫폼을 통해 비즈니스 이해 관계자와 기술 팀 간의 격차를 해소합니다. 따라서 팀 간의 의사 소통이 더욱 투명 해집니다.
#두) 시나리오는 클라이언트 측의 사람, 비즈니스 팀 구성원, 경영진 등 누구나 작성할 수 있습니다. 따라서 요구 사항, 시나리오가 다루어지고 있습니다.
#삼) 개발자는 자신의 이해에 따라 코드를 작성 / 개발하는 대신 BDD 프레임 워크에 작성된 시나리오에 따라 코드를 작성합니다.
# 4) 테스트는 더욱 날카 로워지고 테스트 생성 및 후속 실행에 소요되는 시간이 절약됩니다. 특히 비즈니스에 영향을 미칠 수있는 심각한 결함은 프런트 엔드 자체에서 찾을 수 있습니다.
# 5) BDD와 관련된 코드, 문서는 문서와 해당 코드가 이미 관련되어 있으므로 코드를 유지하는 데 다른 노력이 필요하지 않으므로 쉽게 이해하고 유지 관리 할 수 있습니다. 따라서 문서, 즉 시나리오에 언급 된 내용에는 해당 코드가 있습니다.
# 6) 매우 쉽게 이해할 수있는 시나리오를 가지고 있기 때문에 논리적으로 작업, 하위 작업 등으로 쉽게 나눌 수 있습니다.
# 7) 시나리오, 허용 기준 및 거의 정확한 테스트 추정에 대한 사전 명확성이 있기 때문에 팀은보다 역동적이고 민첩 할 수 있습니다.
# 8) 단순성으로 인해 문서 및 코드 측면에서 기존 팀과 함께 새 조인을위한 매우 좋은 플랫폼입니다.
# 9) 시나리오 (대부분 UI, 동작 관련)의 유효성을 검사하는 데 도움이 될뿐만 아니라 단위 수준 테스트 사례에서도 도움이됩니다.
# 10) 또한 요구 사항과 시나리오가 명확하게 정의되어 있기 때문에 첫날부터 팀의 진행 상황을 추적하는 것이 유용합니다 (개발자가 일반적으로 TDD에서 수집하는 데 어려움을 겪는 것).
따라서 BDD를 구현하면 '최종 고객이 테스트의 중요성에 대해 생각하지 않는다', '클라이언트가 테스트 활동에 참여하기를 원하지 않는다'는 가정이 제거됩니다.
BDD 도구
BDD 접근 방식을 구현할 수있는 몇 가지 테스트 도구가 있습니다.
예 :
- 오이
- SpecFlow
- Jbehave
- 상추
- 콩 코디 언
- FitNesse
- BeanSpec
- 쉬운 B
- Jdave
- Givwenzen-flex
- GivWenZen
- 본능
- 텀블러 유리
- Gospecify
- 스펙 타 큘러
- dSpec
- 명세서
- 스테이크
- JSSpec
위의 도구 중에서 Jbehave는 Cucumber와 매우 유사하게 작동하지만 구현 측면에서 약간 다릅니다.
JBEHAVE | 오이 |
---|---|
외부 데이터 소스 지원 | 외부 데이터 소스를 지원하지 않습니다. |
스토리 지원 | 기능 지원 |
아주 좋은 문서 | 표준 문서 없음 |
복합 단계 지원 | 복합 단계를 지원하지 않습니다. |
유연하지 않음 | 매개 변수 전달의 유연성 |
배경을 지원하지 않음 | 배경 지원 |
그렇게 광범위하지 않은 보고서 | 더 나은 서식 유연성, 기본 제공 보고서 |
Java를 사용하여 개발 | Ruby를 사용하여 개발 |
왜 오이?
Cucumber는 모든 종류의 테스트 케이스, 특히 행동 중심 개발 스타일로 작성된 수락 수준 테스트 케이스 (최종 사용자가 더 관심을 갖는)를 작성하는 데 사용됩니다. Gherkin과 같은 언어 파서의 사용을 지원합니다.
원래 Cucumber는 Ruby 프로그래밍 언어를 사용하여 작성되었으며 특히 Ruby 테스트를 위해 개발되었습니다. 그러나 지금은 Java와 같은 다른 프로그래밍 언어에서 지원되고 있습니다.
Gherkin은 테스트 케이스가 간단한 형식으로 작성되는 언어로 사용되고 있으며 비 기술적 인 사용자도 읽고 수정할 수 있습니다.
영어 외에도 Cucumber는 다른 언어도 지원합니다.
오이는 어떻게 작동합니까?
작동 메커니즘을 살펴보면 먼저 사용자 (기술적 / 비 기술적)가 Gherkin 구문을 사용하여 원하는 테스트 케이스 (기능으로)를 작성할 수 있습니다. 일단 완료되면 승인을 받았는지 확인해야합니다. 다음 단계.
그 후, 기능 파일에 언급 된대로 각 라인 (stepdef 파일 사용)에 대한 스크립트 작성을 구현해야합니다. 코드가 구현되면 다음으로 스크립트를 실행합니다 (러너 파일 사용).
환경 설정
Cucumber의 환경 설정은 Eclipse 또는 다른 IDE와 같은 다른 도구로 작업하는 것에 비해 약간 복잡합니다.
도전
Cucumber jar의 버전이 설치된 Java 버전 및 현재 작업중인 IDE와 일치하는지 확인해야합니다.
환경 설정
# 1) Eclipse Cucumber 플러그인 : Eclipse가 Gherkin 구문을 이해하도록 돕고 일반 텍스트 대신 기능 파일의 구문을 강조합니다.
우리는 가야합니다 Eclipse >> 도움말 >> 새 소프트웨어 설치 >> 추가 버튼 클릭 >> 위치 지정 같이 이 . 이름은 'Cucumber'로 표시된 다음 확인을 클릭하고 나머지 설치 프로세스를 따릅니다.
마지막으로 IDE, 즉 Eclipse를 다시 시작하십시오.
#두) Maven을 사용하여 아래에 언급 된 모든 jar, 즉 종속성, 플러그인 등을 갖습니다.
4.0.0 com cucumber.example 0.0.1-SNAPSHOT jar cucumber.example http://maven.apache.org UTF-8 org.seleniumhq.selenium selenium-java 3.6.0 org.seleniumhq.selenium selenium-chrome-driver 3.6.0 info.cukes cucumber-core 1.2.5 info.cukes cucumber-java 1.2.5 test info.cukes cucumber-junit 1.2.5 test junit junit 4.11 test info.cukes cucumber-testng 1.2.0 info.cukes gherkin 2.12.2 provided log4j log4j 1.2.17 org.apache.poi poi-ooxml 3.9 org.apache.poi poi 3.11-beta3 xml-apis xml-apis 2.0.2 xerces xercesImpl 2.8.0 info.cukes cucumber-jvm-deps 1.0.5 provided org.apache.maven.plugins maven-surefire-plugin 2.18 org.apache.maven.surefire surefire-junit47 2.18
#삼) Ctrl + s 또는 Maven 설치를 수행하는지 확인하십시오.
# 4) 그런 다음 나중에 종속성, 플러그인, 버전 불일치 오류가 발생하지 않도록 Maven 빌드를 수행하여 종속성 관련 오류를 방지하십시오.
Windows 7 용 무료 백업 소프트웨어
# 5) 위의 단계가 완료되면 환경이 준비됩니다.
오이를 사용하여 테스트 케이스 작성
Cucumber에는 다음 세 파일이 포함되어 있습니다.
- 기능 파일 : 여기에서 테스트 할 기능을 Gherkin 형식으로 작성합니다. Stepdef 파일에 작성된 테스트 스크립트를 실행하기 위해 기능 파일을 실행할 수도 있습니다.
- Stepdef 파일 : 기능 파일이 준비되면 기능 파일의 각 문장을 Stepdef 파일 위에 추가로 구현할 수 있습니다.
- 러너 파일 : 기능 파일을 참조하여 Stepdef 파일 위에 작성된 실제 테스트 스크립트를 실행하기위한 것입니다. 그 외에도 사용자 정의,보고, 선택적 실행 등을위한 다른 많은 옵션이 있습니다.
다음은 러너 파일의 간단한 예입니다.
package runner; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features='Features', glue='com.Multi', plugin={'html:target/cucumber-html-report', 'json:target/cucumber.json', 'pretty:target/cucumber-pretty.txt','usage:target/cucumber-usage.json', 'junit:target/cucumber- results.xml'}, dryRun = false, monochrome = true, tags={'@Smoke,@Regression'} ) public class Runner { }
오 이용 파일 생성
- Stepdef 파일 – Src / test / java >> New >> Others >> Cucumber >> StepDef 클래스.
- 기능 파일 – 프로젝트 >> 새로 만들기 >> 파일 >> 확장자가‘.feature’인 파일의 이름을 지정합니다.
- 러너 파일 – 다른 Java 클래스 생성과 유사하지만 여기에서 몇 가지 방법을 구현해야 할 수 있습니다.
오이 특징
다음은 테스트 스크립트에서 구현할 Cucumber의 기본 기능 중 일부입니다.
# 1) 오이 갈고리
이는 각 시나리오 전후에 실행되는 코드 블록입니다. 그래서 우리는 프로젝트의 어느 곳에서나 이것을 정의 할 수 있습니다. 예를 들어, 단계 정의.
정의에 따라 @After 및 @Before 두 개의 주석입니다. 콘솔에서 블록이 실행되고 명확한 출력을 제공하는 것을 볼 수 있습니다. 특정 태그에 대한 후크를 실행할 수도 있습니다.
# 2) 오이 태그
이들은 일반적으로 주어진 태그 이름에 따라 기능 파일에 대한 시나리오를 분류하기 위해 기능 파일에 사용됩니다. 기능 파일에서 특정 시나리오에 대해 여러 태그를 가질 수 있습니다.
태그는 사용자 정의되며 @Smoke, @Regression 등과 같은 이름을 지정할 수 있습니다.
# 3) 오이 주석
이것들은 오이에 내장되어 있습니다. 일반적으로 태그는 @Given, @When, @Then입니다.
그러나 나중에 필요한 경우 자체 주석을 만든 다음 프로그램에서 사용할 수 있습니다. 실행하는 동안 일치하는 글루 코드, 즉 함수는 @Given, @When, @Then이있는 Stepdef 파일에 작성됩니다.
# 4) 오이 배경
기능 파일의 모든 시나리오에 공통적 인 단계 또는 일련의 단계입니다.
이를 통해 정의 된 기능에 대한 시나리오에 몇 가지 컨텍스트를 추가 할 수 있습니다. 정의 된 기능에 대한 모든 시나리오 전에 실행됩니다.
# 5) 오이 데이터 테이블
Cucumber에는 데이터 기반 테스트를 지원하는 기능이있어 주어진 스크립트에 대해 다른 입력 및 유효성 검사 값을 사용하여 테스트 케이스를 여러 번 자동으로 실행할 수 있습니다.
Cucumber는 데이터 테이블을 지원합니다. 첫 번째 행은 열로 간주되고 그 옆에있는 행은 스크립트에 대한 데이터입니다.
# 6) 오이 조옮김
이것은 Cucumber 데이터 테이블을 약간 수정 한 것입니다. 여기서 첫 번째 열은 열로 간주되고 다음 열은 스크립트의 데이터로 간주됩니다.
# 7) 오이 다중 시나리오
Cucumber를 사용하면 하나의 기능 파일에서 여러 시나리오를 테스트 할 수 있습니다.
# 8) 오이보고
보고를보기 위해 일부 구성을 수행해야하는보고 및 기타 타사 도구와 달리.
여기 Cucumber에는 테스트 실행에 대한 포괄적 인 보고서를 제공하는 pretty, JSON, HTML, XML과 같은 플러그인이 내장되어 있습니다.
오이로 TestNG
우리는 여전히 TestNG를 사용하여 Cucumber로 작성된 JUnit 테스트 케이스를 실행할 수 있습니다. 다음으로 :
- Maven 프로젝트에 종속성을 추가해야합니다.
- Runner 클래스의 클래스를 AbstractTestNGCucumberTests 패키지 러너로 확장합니다.
- Maven 프로젝트를 변환하고 패키지를 추가합니다 (runner 클래스가있는 위치).
그 후 전체 Cucumber 테스트 케이스를 TestNG로 실행하고 동일한 관련 보고서를 생성 할 수 있습니다 (리스너가있는 경우).
이 튜토리얼에서는 위의 개념을 다루기 위해 3 가지 Cucumber 예제에 대해 설명합니다.
예 1
Cucumber를 사용한 후크, 태그, 주석, 배경, 여러 시나리오 및 TestNG를 다룹니다.
테스트 환경이 설정되면 :
- Eclipse에 Eclipse Cucumber 플러그인을 추가합니다.
- Maven 프로젝트를 만들고 필요한 모든 종속성을 추가하고 Maven에 TestNG 관련 종속성도 추가합니다.
- 새 기능 파일을 만듭니다.
- Stepdef 파일에 필요한 구현을 추가하십시오.
- 이제 extends AbstractTestNGCucumberTests를 사용하여 러너 파일을 만듭니다.
- Maven 프로젝트를 TestNG로 변환하고 testng.xml에서 Cucumber 러너 클래스의 패키지 경로를 추가합니다.
- TestNG.xml 파일을 실행하십시오.
기능 파일
특색:
사용자로서
시스템에 새 클라이언트를 추가하고 싶습니다.
해당 클라이언트에 대한 회계 데이터를 추가 할 수 있도록
배경:
내가 Github 홈페이지에 있다는 것을 감안할 때
사용자 이름을 'xxxxxxxxxxxxxxxxxxxx'로 지정하고 암호를 'xxx'로 지정한 경우
그리고 로그인 버튼을 클릭하십시오
@연기
대본: 프로필 편집
귀하의 프로필 옵션을 클릭하면
프로필 편집 버튼을 클릭하면
그리고 업로드 된 새 사진
그러면 새 프로필 사진이 보여야합니다
@Regression @ 매번
대본: 새로운 요점 만들기
귀하의 요점 옵션을 클릭하면
파일 이름, 설명을 제공 할 때
그리고 Create public gist method를 클릭합니다.
그럼 난 새로운 요점을 봐야 겠어
Stepdef 파일
package com.Multi; import cucumber.api.PendingException; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.But; import java.util.List; import cucumber.api.PendingException; import cucumber.api.java.it.Data; import cucumber.runtime.ScenarioImpl; import gherkin.formatter.model.Scenario; import gherkin.formatter.model.ScenarioOutline; import cucumber.api.DataTable; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import cucumber.api.cli.Main; public class Step2 { static public String sb; static public String sa; static WebDriver driver = null; @Before('@Smoke,@Regression') public void beforeScenario(){ System.out.println('New scenario begins'); } @After('@Smoke,@Regression') public void afterScenario(){ System.out.println('Scenario ends'); } @MyAnnotation public static void myanno() { System.out.println('my annot gets executed'); } @Given('^I am on Github home page$') public void i_am_on_Github_home_page(){ String site = 'https://www.github.com/login'; System.setProperty('webdriver.chrome.driver', 'Executables\chromedriver.exe'); driver = new ChromeDriver(); driver.navigate().to(site); //driver.findElement(By.cssSelector('a(contains(@href, 'login'))').click(); // Write code here that turns the phrase above into concrete actions } @When('^I specify Username as '((^')*)' and Password as '((^')*)'$') public void i_specify_Username_as_and_Password_as(String arg1, String arg2){ driver.findElement(By.cssSelector('input#login_field')).sendKeys(arg1); driver.findElement(By.cssSelector('input#password')).sendKeys(arg2); // Write code here that turns the phrase above into concrete actions } @When('^Click on SignIn button$') public void click_on_SignIn_button(){ driver.findElement(By.cssSelector('input.btn')).click(); // Write code here that turns the phrase above into concrete actions } @Given('^I click on Your Profile option$') public void i_click_on_Your_Profile_option(){ driver.findElement(By.xpath('//*(@id='user -links')/li(3)/details/summary/img')).click(); List olist = driver.findElements(By.xpath('//*(@id= 'user-links')/li(3)/details/ul/li/a(@class='dropdown-item')')); for(WebElement o:olist) { if(o.getText().equals('Your profile')) { o.click(); break; } } // Write code here that turns the phrase above into concrete actions } @When('^I click on edit profile button$') public void i_click_on_edit_profile_button(){ driver.findElement(By.xpath('//*(@id='js-pjax -container')/div/div(2)/div(1)/a')).click(); // Write code here that turns the phrase above into concrete actions } @When('^Uploaded new picture$') public void uploaded_new_picture() throws InterruptedException{ WebElement s1 = driver.findElement(By.xpath('//*(@class='avatar-upload -container clearfix')/Img')); sb=s1.getAttribute('src'); System.out.println(s1.getAttribute('src')); driver.findElement(By.id('upload-profile -picture')).sendKeys('D://cucumberFinal//multiple//Files//images.jpg'); Thread.sleep(10000); String wh = driver.getWindowHandle(); driver.switchTo().window(wh); Actions actions = new Actions(driver); WebElement element = driver.findElement(By.xpath('//div(@class='facebox -content')/form/div(3)/button')); Thread.sleep(10000); actions.moveToElement(element); //Thread.sleep(10000); actions.click(); //actions.sendKeys('GIST1 Description'); actions.build().perform(); // driver.findElement(By.xpath('//div(@class='facebox -content')/form/div(3)/button')).click(); Thread.sleep(3000); // Write code here that turns the phrase above into concrete actions } @Then('^I should be seeing new profile picture$') public void i_should_be_seeing_new_profile_picture(){ WebElement s1 = driver.findElement(By.xpath('//*(@class='avatar-upload -container clearfix')/Img')); sb=s1.getAttribute('src'); System.out.println(s1.getAttribute('src')); if(!(sb.equals(sa))) { Assert.assertTrue('File Upload successful', true); } // Write code here that turns the phrase above into concrete actions } @Given('^I click on Your Gists option$') public void i_click_on_Your_Gists_option(){ driver.findElement(By.xpath('//*(@id='user-links')/li(3)/details/summary/img')).click(); List olist = driver.findElements(By.xpath('//*(@id= 'user-links')/li(3)/details/ul/li/a(@class='dropdown-item')')); for(WebElement o:olist) { if(o.getText().equals('Your Gists')) { o.click(); break; } } // Write code here that turns the phrase above into concrete actions } @When('^I provide filename, description$') public void i_provide_filename_description() throws InterruptedException { // Write code here that turns the phrase above into concrete actions driver.findElement(By.xpath('//div(@class='edit container')/div(@id='gists')/input')).sendKeys('Gist1'); Thread.sleep(2000); Actions actions = new Actions(driver); WebElement element = driver.findElement(By.xpath('//*(@id='gists')/div(2)/div/div(2)/div/div(5)/div(1)/ div/div/div/div(5)/div/pre/span')); actions.moveToElement(element); actions.click(); actions.sendKeys('GIST1 Description'); actions.build().perform(); // driver.findElement(By.xpath('//*(@id='gists')/div(2)/div/div(2)/div/div(5)/div(1)/ div/div/div/div(5)/div/pre/span')).sendKeys('GIST1 Description'); Thread.sleep(2000); } @When('^click on Create public gist method$') public void click_on_Create_public_gist_method() { driver.findElement(By.xpath('//*(@id='new_gist')/div(2)/div(2)/button(1)')).click(); // Write code here that turns the phrase above into concrete actions } @Then('^i should be seeing the new gist$') public void i_should_be_seeing_the_new_gist(){ List glist = driver.findElements(By.xpath('//div(@class='container repohead-details- container')/ul(1)/li(@class='flex-auto')/div/a')); for(WebElement o:glist) { if(o.getText().equals('Gist1')) { System.out.println('Gist created successfully'); } } // Write code here that turns the phrase above into concrete actions } }
TestNG XML의 테스트 결과는 다음과 같습니다.
기본 TestNG 보고서는 다음과 같습니다.
예 2
데이터 테이블을 다루고 전치합니다.
환경이 설정되면 :
- Eclipse에 Eclipse Cucumber 플러그인을 추가합니다.
- Maven 프로젝트를 만들고 필요한 모든 종속성을 추가합니다.
- 새 기능 파일을 만듭니다.
- stepdef 파일에 필요한 구현을 추가하십시오.
- 파일 >> Run as >> Cucumber.feature를 마우스 오른쪽 버튼으로 클릭하여 기능 파일에서 직접 실행
기능 파일
특색: 기능 제목
내 기능 파일에이 템플릿을 사용하고 싶습니다.
배경:
내가 Gmail 로그인 페이지에있는 경우
사용자 이름과 비밀번호를 지정할 때
그리고 로그인 버튼을 클릭하십시오
대본: 데이터 테이블에서 새 메시지 만들기
새 이메일 페이지에있을 때
그리고 다음 세부 사항을 지정합니다.
| To1 | 주제 |
| Person1@email.com | Person1 주제 |
| Person2@email.com | Person2 주제 |
대본: 전치 된 데이터 테이블에서 새 메시지 만들기
새 이메일 페이지에있을 때
그리고 전치 테이블에서 다음 세부 정보를 지정합니다.
| To1 | Person1@email.com | Person2@email.com |
| 주제 | Person1 주제 | Person2 주제 |
Stepdef 파일
package com.datatable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.time.*; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import cucumber.api.DataTable; import cucumber.api.Transpose; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import gherkin.formatter.model.Examples; import cucumber.runtime.CucumberException; import cucumber.runtime.ParameterInfo; import cucumber.runtime.xstream.LocalizedXStreams; public class Step3 { static public WebDriver driver; @Given('^I am on Gmail login page$') public void i_am_on_Gmail_login_page() throws InterruptedException{ System.setProperty('webdriver.chrome.driver', 'Executables/chromedriver.exe'); driver= new ChromeDriver(); Actions act = new Actions(driver); driver.manage().window().maximize(); driver.navigate().to('https://www.google.com/gmail/about'); driver.findElement(By.xpath('//nav/div/a(2)')).click(); Thread.sleep(3000); } @When('^I specify Username and Password$') public void i_specify_Username_and_Password() throws InterruptedException{ driver.findElement(By.xpath('//input(@type='email')')).sendKeys('xxxxxx@xxx. com'); driver.findElement(By.xpath('//*(@id='identifierNext')/content/span')).click(); Thread.sleep(3000); driver.findElement(By.xpath('//input(@type='password')')).sendKeys('xxxxxxxx xxx'); } @When('^Click on SignIn button$') public void click_on_SignIn_button() throws InterruptedException{ driver.findElement(By.xpath('//*(@id='passwordNext')/content/span')).click(); Thread.sleep(5000); } @When('^I am on New Email Page$') public void i_am_on_New_Email_Page(){ } @When('^I specify following details$') public void i_specify_following_details(DataTable tables)throws Throwable{ for (Map row : tables.asMaps(String.class, String.class)) { driver.findElement(By.xpath('//*(@id=':x4')/div/div')).click(); //driver.switchTo(). System.out.println(row.get('To1')); System.out.println(row.get('Subject')); String whandle = driver.getWindowHandle(); driver.switchTo().window(whandle); driver.findElement(By.xpath('//td(@class='eV')/div(1)/div/textarea')).sendKeys (row.get('To1')); driver.findElement(By.xpath('//table(@class='aoP aoC bvf')/tbody/tr/td/form/div(3)/input')).sendKeys(row.get('Subject')); driver.findElement(By.xpath('//table(@class='IZ')/tbody/tr/td/div')).click(); Thread.sleep(3000); } } @When('^I specify following details from transpose table$') public void i_specify_following_details_from_transpose_table(DataTable tables) throws InterruptedException { // DataTable tables = null; for (Map row : tables.transpose().asMaps(String.class, String.class)) { driver.findElement(By.xpath('//*(@id=':x4')/div/div')).click(); //driver.switchTo(). Thread.sleep(2000); System.out.println(row.get('To1')); System.out.println(row.get('Subject')); String whandle = driver.getWindowHandle(); driver.switchTo().window(whandle); driver.findElement(By.xpath('//td(@class='eV')/div(1)/div/textarea')).sendKeys (row.get('To1')); Thread.sleep(3000); driver.findElement(By.xpath('//table(@class='aoP aoC bvf')/tbody/tr/td/form/div(3)/input')).click(); driver.findElement(By.xpath('//table(@class='aoP aoC bvf')/tbody/tr/td/form/div(3)/input')).sendKeys(row.get('Subject')); Thread.sleep(3000); driver.findElement(By.xpath('//table(@class='IZ')/tbody/tr/td/div')).click(); Thread.sleep(3000); } } @When('^then click on Send button$') public void then_click_on_Send_button(){ // Write code here that turns the phrase above into concrete actions } @Then('^I should be able to send the email successfully$') public void i_should_be_able_to_send_the_email_successfully() { // Write code here that turns the phrase above into concrete actions }
산출 : 따라서 위의 예는 Gmail에 로그인하고 데이터 테이블 및 전치 된 데이터 테이블에 대한 시나리오별로 두 개의 이메일을 보냅니다.
예제 3
보고를 다룰 것입니다.
환경이 설정되면 :
- Eclipse에 Eclipse Cucumber 플러그인을 추가합니다.
- Maven 프로젝트를 만들고 필요한 모든 종속성을 추가합니다.
- 새 기능 파일을 만듭니다.
- Stepdef 파일에 필요한 구현을 추가하십시오.
- 러너 클래스를 만들고 러너 클래스를 실행합니다.
- 모든 유형의 보고서를 봅니다.
기능 파일
특색: 기능 제목
내 기능 파일에이 템플릿을 사용하고 싶습니다.
@ tag1
대본: 시나리오 제목
내가 Github 홈페이지에 있다는 것을 감안할 때
사용자 이름과 비밀번호를 지정할 때
그리고 로그인 버튼을 클릭하십시오
그러면 로그 아웃 옵션을 볼 수있을 것입니다
Stepdef 파일
package com.cucumber; import cucumber.api.PendingException; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.api.java.en.But; import java.util.List; import cucumber.api.PendingException; import cucumber.api.java.it.Data; import cucumber.api.DataTable; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import cucumber.api.cli.Main; public class Step1 { static WebDriver driver = null; @Given('^I am on Github home page$') public void i_am_on_Github_home_page(){ String site = 'https://www.github.com/login'; System.setProperty('webdriver.chrome.driver', 'Executables\chromedriver.exe'); driver = new ChromeDriver(); driver.navigate().to(site); //driver.findElement(By.cssSelector('a(contains(@href, 'login'))').click(); // Write code here that turns the phrase above into concrete actions } @When('^I specify Username and Password$') public void i_specify_Username_and_Password() { driver.findElement(By.cssSelector('input#login_field')).sendKeys('chintamoni .patra@gmail.com'); driver.findElement(By.cssSelector('input#password')).sendKeys('Test@123'); // Write code here that turns the phrase above into concrete actions } @When('^Click on SignIn button$') public void click_on_SignIn_button(){ driver.findElement(By.cssSelector('input.btn')).click(); // Write code here that turns the phrase above into concrete actions } @Then('^I should be able to see logout option$') public void I_should_be_able_to_see_logout_option() throws InterruptedException{ driver.findElement(By.xpath('//*(@id='user -links')/li(3)/details/summary/img')).click(); WebElement opt = driver.findElement(By.xpath('//*(@id='user- links')/li(3)/details/ul/li')); List olist = opt.findElements(By.xpath('//li/form/button')); for(WebElement o : olist) { System.out.println(o); } //int a = olist.size(); System.out.println(olist.get(0).getText()); olist.get(0).click(); Thread.sleep(2000); // Write code here that turns the phrase above into concrete actions } }
다음은 Cucumber에서 생성하는 다양한 유형의 보고서입니다.
HTML 보고서
예쁜
Junit
결론
오픈 소스 도구 인 Cucumber는 BDD에서 널리 사용됩니다. 그리고 이해하기 매우 쉽고 새로운 기능과 관련하여 많은 범위를 가지고 있으며 Cucumber를 Selenium 또는 기타 타사 도구 / 단지 등과 통합하는 것이 실제로 가능합니다.
활동적인 도움말 그룹 / 회원이 있기 때문에 Cucumber를 방금 배우기 시작한 사람이나 Cucumber / BDD에 대한 중급 지식이있는 사람에게 정말 쉬워집니다.
Cucumber는 Excel 시트 및 Jenkins와의 통합도 지원합니다.
추천 도서
- Cucumber Selenium 튜토리얼 : Cucumber Java Selenium WebDriver 통합
- 예제가 포함 된 Python DateTime 자습서
- BDD 접근 방식을 사용하는 Cucumber로 REST API 테스트
- Cucumber Tool과 Selenium을 사용한 자동화 테스트 – Selenium Tutorial # 30
- Cucumber Gherkin 자습서 : Gherkin을 사용한 자동화 테스트
- 예제가 포함 된 Unix 쉘 스크립팅 자습서
- 예제와 함께 텍스트 자습서로 셀레늄 찾기 요소
- Java 'this'키워드 : 코드 예제가 포함 된 자습서