이 기사에서는 스프링 부팅을 오이 (BDD)에 통합하는 방법을 소개하고이를 공유합니다. 세부 사항은 다음과 같습니다.
1. 다음과 같이 새 스프링 부츠 프로젝트 구조를 만듭니다.
2. POM 종속성을 추가하십시오
<? xml version = "1.0"encoding = "utf-8"?> <project xmlns = "http://maven.apache.org/pom/4.0.0"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance" xsi : schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion> 4.0.0 </modelversion> <groupid> com.chhhliu </grouphiid> artifactid> spring-cucucuc < <버전> 0.0.1-snapShot </version> <packaging> jar </packaging> <name> Spring-boot-cucumber </name> <description> 스프링 부팅 및 오이를위한 데모 프로젝트 </descript> <perge> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid>. <RelativePath/> <!-리포지토리에서 부모를 조회합니다-> </parent> <cucumber> <cucumber.version> 1.2.4 </cucumber.version> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> <project.ropporting.outpepencoding> utf-8 <porting.reout.reout.reout. <java.version> 1.7 </java.version> </properties> <pectionements> <pectionement> <groupId> org.springframework.boot </groupid> <atifactid> spring-boot-starter-web </artifactid> </dependency> <groupid> info.cukes </groupid> <artifactid> Cucumbumber-Java </artifactid> <bersion> $ {cucumber.version} </version} </version> </expendency> <pectionency> <groupid> info.cukes </groupId> <artifactid> cucumber-core </artifactid> <bersion> $ {cucumber.version} </felevency> <groupid> info.cukes </groupid> <artifactid> Cucumber-Spring </artifactid> <bersion> $ {cucumber.version} </version> </dependency> <prectionement> <groupid> info.cukes </groupId> <artifactid> cucumber-junit </artifactid> <version> $ {cucumbert <제외> <groupId> junit </groupId> <artifactID> junit </artifactid> </제외> </exclusions> </fexendency> <pectionency> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-test </arepifact> </scope> </scope> </scope> </scope> </scope> </scope> <플러그인> <groupid> org.springframework.boot </groupid> <artifactid> Spring-Boot-Maven-Plugin </artifactid> <configuration> <court> 1.7 </source> <garget> 1.7 </target> </configuration> </plugin> <flugin> groupid> org.codeha. <아티 팩트> exec-maven-plugin </artifactid> <configuration> <court> 1.7 </source> <garget> 1.7 </target> </configuration> <executions> <ceputions> <come> integration-test </phase> <Goals> <Goal> java </Goal> </Goals> <classPathscope> test </classpathscope> <mainclass> com.chhliu.test.cucumbertest.java </mainclass> <arguments> <hartument>-플러그인> <argument> pretty </argument> <athument>-Glue </argument> <argument> src/test/resources/</argument> </configurition> </execution> </execution> </execution> </execution> </빌드> </project>2. 서비스 인터페이스 및 구현 클래스를 작성하십시오
패키지 com.chhliu.service; / ** * 시뮬레이션 로그인 * @author chhliu * */ public 인터페이스 userInfoservicei {boolean login (문자열 사용자 이름, 문자열 암호, 문자열 확인 password); } 패키지 com.chhliu.service; org.springframework.stereotyp.service; @Service ( "userInfoservice") public class userInfoservice는 userInfoservicei {public boolean login (string username, string password, string quickPassword) {return (username.equals ( "chhliu") && password.equals ( "123456") && quiclaspword.equals ( "12345")를 구현합니다. }} 3. 기능 파일을 작성하십시오
#language : zh-cn # "zh-cn": { # "그러나": "*| | 그러나 <", # "및": "*| and <| and <| and <| and <| and <| and <| 및 <|"*| so < ", #": "*| <", # "name": "simplified", # ":"Simplified Chinese "", # "" "" "" "" "" "": "": " "배경", # "시나리오": "시나리오 _outline": "시나리오 개요 | 스크립트 개요", # "예제": "예제", "예제", # "주어진": "*| if <| if <| if <| if <| if <| if <" #} @bank 기능 : 내가 끊임없이 입력하고 비밀번호에 입력 한 경우, 내 은행에 입력 한 경우, 내 은행에 입력 한 경우. 잔액이 500,000 인 경우 : 시나리오 : 은행은 다음과 같은 경우 돈을 인출하고 다음과 같이 입력 한 비밀번호는 "123456"입니다. 4. 테스트 클래스를 작성하십시오
패키지 com.chhliu.test; import org.junit.runner.runwith; cucumber.api.cucumberoptions import; import cucumber.api.junit.cucumber; /*** @runwith (cucumber.class) 이것은 러너입니다. 이것은 오이를 사용하여 테스트를 실행하기 위해 오이를 사용하는 것입니다.* @cucumberoptions* @cucumberoptions를 실행하는 기능의 디렉토리를 지정합니다.* @cucumberoptions 형식에서 실행할 기능의 디렉토리를 지정합니다. 프로젝트가 실제 프로젝트에서 실행될 때 단계 정의 파일을 찾는 디렉토리를 지정하고 프로젝트가 진행됨에 따라 테스트 프로젝트는 여러 기능 파일로 구성 될 수 있으며 각 기능 파일은 여러 시나리오로 구성 될 수 있습니다. 기본적으로 * 각 실행은 모든 기능에서 모든 시나리오를 실행하는 것입니다. 이로 인해 정상적인 상황에서 테스트 스크립트가 한 번 실행되므로 테스트 결과를 기다리는 데 시간이 오래 걸립니다. 그러나 실제 과정에서 테스트 사례는 우선 순위로 구별됩니다. 예를 들어, Smoketest, Regresstest 등 또는 때로는 레벨과 같은 소규모 사용 사례가 특히 중요합니다. * 이러한 사용 사례는 시스템에 흰색 페이지가 없는지 여부를 모니터링하기 위해 장기 작업이 필요합니다. * 모든 시나리오를 구별해야하므로 테스트 스크립트를 시작할 때 필요한 모듈을 실행할 수 있습니다. 현재 오이로 태그 *를 사용할 수 있으며 태그는 피처, 시나리오 개요 키워드 전에 피처 또는 시나리오에 접두사 @가있는 수많은 태그를 직접 추가하고 여러 태그가 공백으로 분리됩니다 * @author chhliu * */ @runwith (cucumber.class) @cucuricoptions (plugin = json : json. "Pretty"}, feature = "src/test/resources") 공개 클래스 CucumberTest {} 5. 테스트 클래스를 실행하고 테스트 출력의 정의되지 않은 단계를 향상시킵니다.
패키지 com.chhliu.test; import javax.annotation.resource; import org.junit.assert; com.chhliu.service.userinfoservicei import; import cucumber.api.java.zh_cn.if; cucumber.api.java.zh_cn. 시간; import cucumber.api.java.zh_cn.so; 공개 클래스 오이 통합 스프링 {@resource (name = "userInfoservice") private userInfoservicei 서비스; 개인 문자열 사용자 이름; 개인 문자열 비밀번호; 개인 문자열 quictpassword; @if ( "^: 나는 $ with/"([^/"]*)/"$ ") public void I log i log in (string arg1) 던지기 가능 {this.username = arg1;} @if ("^: 입력 된 암호는/"$") public void가 입력 한 비밀번호가 입력 한 (String arg1) throws trowne {this. } @When ( "^: 암호는 또한/"([^/"]]*)/"$ ") 공개 void 암호 확인 암호도 _ (String arg1) throws {this.confirmpassword = arg1;} @Then ("^: 은행 카드 잔액은/"([^/"]*)/"$")를 보여줍니다 service.login (사용자 이름, 비밀번호, 확인 password); if (islogin) {system.out.println ( "성공적으로 로그인! 쿼리 밸런스는 다음과 같습니다."+arg1); assert.assertequals ( "500000", arg1); }}} 6. 테스트 단계에 주석 지지대를 추가하십시오
@RunWith (SpringJunit4classRunner.class) @contextConfiguration //이 주석이 추가되지 않으면 Bean이 주입되어 @SpringBoottest를 주입 할 수 없습니다. //이 주석이 추가되지 않으면 공개 클래스 오이 통합 스프링 {} 7. 테스트 결과
2 개의 시나리오 (2 통과)
11 단계 (11 통과)
0m0.091S
8. 통합 지점
Spring Boot를 Cucumber와 통합 할 때 Spring Boot는 De-Xmlization을 옹호하기 때문에주의를 기울여야 할 지점이 있습니다. 따라서 기존의 방식으로 Cucumber는 Cucumber.xml 구성 파일을 클래스 경로 아래에서 읽어 Bean을 초기화합니다. Spring과 통합 한 후이 방법을 사용할 수 없습니다. 클래스로드를 구현하려면 @ContextConfiguration 주석을 사용해야합니다. 구성 파일을로드 해야하는 경우 다음과 같이 사용할 수 있습니다.
@contextConfiguration (locations = { "classPath : ApplicationContext.xml"})주석을 사용하여 통합하는 경우 다음을 사용하십시오.
@contextConfiguration (classment = springbootcucumberApplication.class)
또는 직접
@contextConfiguration
특별 참고 : @contextConfiguration 주석을 추가해야합니다. 그렇지 않으면 Bean 주입이 실패합니다.
다음 으로이 상황이 소스 코드에서 발생하는 이유를 살펴 보겠습니다.
이 부분과 관련된 코드는 오이 스프링 패키지의 SpringFactory 클래스에 있습니다. 다음 수업을 살펴 보겠습니다.
public void start () {// cucumber test start method if (stepClassWithSpringContext! = null) {// @ContextConfiguration 주석이 사용되면 NULL TestContextManager = New CucucumberTestContTmanager (stepClassWithSpringContext)가 아닙니다. } else {// 그렇지 않으면 stepClasswithSpringContext가 null이되며 다음 지점에 입력됩니다. if (beanFactory == NULL || isnewContextCreated ()) {beanFactory = testContextManager.getBeanFactory (); for (class <?> stepClass : stepClass) {registerStepClassBeanDefinition (beanFactory, stepClass); }} gluecodecontext.instance.start (); } CreateEfallbackContext 메소드를 따르겠습니다.
private configurablelistableBeanFactory createFallbackContext () {configurablePplicationContext ApplicationContext; if (getClass (). getClassLoader (). getResource ( "cucumber.xml")! = null) {// <font-family : arial, helvetica, sans-serif; "> configurableApplicationcontext = new classxmlapplicationcontext (" "); } else {// cucumber.xml이 구성되지 않은 경우 새로운 genericapplicationcontext = new GenericApplicationContext (); } ApplicationContext.registerShutdownHook (); configurableIstableBeanFactory beanFactory = ApplicationContext.getBeanFactory (); beanfactory.registerscope (gluecodescope.name, new gluecodescope ()); for (class <?> stepClass : stepClass) {registerStepClassBeanDefinition (beanFactory, stepClass); } 반환 beanfactory; }마지막으로 GenericApplicationContext 클래스에 대해 이야기 해 봅시다. 이 클래스는 Bean의 유형과 NewInstance 인스턴스를 기반으로합니다. 그러나 다른 클래스 가이 클래스에 주입되므로, 주입 된 클래스는 새 인스턴스를 통해 초기화 될 수 없으므로 주입이 실패하고 널 포인터 가보고됩니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.