test4j场景化测试

初步文档见此
https://github.com/test4j/test4j.doc

1.场景化测试

之前的单元测试只接触过单一的测试用例,test4j中存在一种场景化的测试方案,先初步来感受一下

1.1 BeforeScenarioDemo继承自JSpec
1.2 代码中出现了@Given,@When, @Then3个对方法进行修饰的注解
1.3 @Named修饰方法参数

public class BeforeScenarioDemo extends JSpec {
    private Integer var = 0;

    @Given
    public void setVar(final @Named("变量值") Integer var//
) throws Exception { this.var = var; } @When public void addVar(final @Named("增量") Integer inc//
) throws Exception { this.var += inc; } @Then public void checkVar(final @Named("变量值") Integer expected//
)throws Exception { want.number(var).isEqualTo(expected); } }

2.BeforeScenarioDemo.story

BeforeScenario
Given set var
    设置【变量值=23】
    
Scenario 给变量值加增量
When add var
    给变量值增加【增量=10】
    
Then check var
    检查【变量值=33】  

以Given set var为例,Given表示对应的注解,set var表示对应的方法,也可以写成setVar

测试结果:

====================Begin Scenario-01: 给变量值加增量====================
* SUCCESS Given : setVar
* SUCCESS When  : addVar
* SUCCESS Then  : checkVar
====================End Scenario-01: 给变量值加增量====================

2.Spring支持

使用@SpringContext添加spring配置文件

@SpringContext("spring-config.xml")
public class TestDemo extends Test4J {

    @Autowired
    private TestService testService;

    @Test
    public void test1()
    {
        testService.sayHello();
    }
}

3.step分步测试

使用Mix注解可以实现分步测试

@Mix({ StepsDemo1.class, StepsDemo2.class, StepsDemo3.class })
@SpringContext("spring/spring-demo.xml")
public class StepsSpec extends JSpec {

    @Override
    protected void initSharedData() {
        this.shared = new MyName();
    }

    public static class MyName implements SharedData {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

public class StepsDemo1 extends Steps.Default {

    private String name;
    /**
     * 验证框架自动给Steps的子类注入spring bean的功能
     */
    @SpringBeanByName
    UserService    userService;

    @Given
    public void method1(final @Named("测试数据") String name) {
        want.object(userService).notNull();
        this.name = name;
        super.shared.setName(name);
    }

    @When
    public void doing() throws Exception {
        want.object(userService).notNull();
        this.name = "hello, " + this.name;
    }

    @Then
    public void checkPara(final @Named("验证数据") String expected//
) throws Exception { want.object(userService).notNull(); want.string(name).isEqualTo(expected); } } public class StepsDemo2 extends Steps.Default { @Step public void printSomething() { System.out.println("print name:" + super.shared.getName()); } } public class StepsDemo3 { @Step public void printSomething3() { System.out.println("print name, no shared data"); } }

你可能感兴趣的:(test4j场景化测试)