目前Spring-boot成为了java开发的主流框架,Cucumber作为一款支持dsl的自动化测试工具,很适合用户编写DSL优化过的单元测试等测试用例。本文将讲解如何在SpringBoot中配置Cucumber进行自动化测试。
目录结构如下:
、
gradle相关配置如下所示:
- <properties>
- <!-- 集成测试依赖 -->
- <cucumber.java.version>1.2.5</cucumber.java.version>
- </properties>
- <!--start 集成测试 -->
- <dependency>
- <groupId>org.glassfish.jersey.core</groupId>
- <artifactId>jersey-common</artifactId>
- <version>2.22.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>info.cukes</groupId>
- <artifactId>cucumber-core</artifactId>
- <version>${cucumber.java.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>info.cukes</groupId>
- <artifactId>cucumber-java</artifactId>
- <version>${cucumber.java.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>info.cukes</groupId>
- <artifactId>cucumber-junit</artifactId>
- <version>${cucumber.java.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>info.cukes</groupId>
- <artifactId>cucumber-spring</artifactId>
- <version>${cucumber.java.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.github.javafaker</groupId>
- <artifactId>javafaker</artifactId>
- <version>0.14</version>
- <scope>test</scope>
- </dependency>
- <!--end 集成测试 -->
复制代码src中为常见的spring代码结构,我们不再具体讲解。test文件夹中上边为自带的SpringBootTest测试框架,而demo中的内容是Cucumber框架的具体配置。 1.首先我们需要配置基本的Cucumber框架CucumberTest.java: - @RunWith(Cucumber.class)
- @CucumberOptions(features = "src/test/resources")
- public class CucumberTest {
- }
复制代码2.接下来,我们要配置有关Spring-boot的配置,因为我们的测试框架也需要在springboot的运行下完成AbstractDefs.java: - @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(classes = TestSpringMongoApplication.class)
- @WebAppConfiguration
- @SpringBootTest
- public class AbstractDefs
- {
- }
复制代码3.然后,我们便开始写属于我们的DSL解析语法,可具体的测试流程TestSteps.java: - import com.tiandi.service.FaultInjectionInfoService;
- import cucumber.api.java.en.And;
- import cucumber.api.java.en.Given;
- import cucumber.api.java.en.Then;
- import cucumber.api.java.en.When;
- import org.springframework.beans.factory.annotation.Autowired;
- public class TestSteps extends AbstractDefs {
- @Autowired
- private FaultInjectionInfoService faultInjectionInfoService;
- private String faultNodeId;
- @Given("^Generate testCase for \"([^\"]*)\"$")
- public void generateTestCase(String id) {
- faultNodeId = id;
- }
- @Then("^finish$")
- public void finish() {
- faultInjectionInfoService.generateTestCase(faultNodeId);
- }
- }
- //在这里,我们通过Autowired注入了spring中的service,并编写用户自定义的DSL来调用service中的方法执行,获得测试结果。
复制代码4.最后,我们在resources中填写具体的黄瓜测试用例,并执行。 - Feature: test cucumber
- Scenario: system out print something
- Given Generate testCase for "COM-COM-F"
- Then finish
复制代码5.测试结果如图所示 绿色代表测试通过
|