【JBehave】集成spring测试

  通过研究网上的教程(这儿说一句,网上关于jbehave的教程确实有点少)和官网的文档,完成了基于jbehave和spring的整合测试案例,现将相关的代码发出来,供大家。

  博主后期应该会大量使用jbehave,大家有什么问题可以一起交流。


1、根据测试场景,编写相应的story。

Meta:

Narrative:
As a user
I want to login into system and i will own my right

Scenario: system admin login
Given uid is v3admin@v3 and password is 123456
When i login
Then i have role manager


Scenario: company admin login
Given uid is chenshengli@zyqckjcd and password is 123456
When i login
Then i have role company_manager

在这个story中,包含两个场景的测试,其一是系统管理员登陆,其二是公司管理员登陆


2、编写对应的step java

@Component
public class LoginSteps {

    private String uid;

    private String password;

    private User user;

    @Autowired
    private UserService userService;

    @Given("uid is $uid and password is $password")
    public void init(String uid, String password) {
        this.uid = uid;
        this.password = password;
    }


    @When("i login")
    public void login() throws V3Exception {
        System.out.println(uid + "," + password);
        this.user = userService.login(uid, password);
    }

    @Then("i have role $role")
    public void check(String role) {
        assertTrue(user.getRoles().contains(role));
    }

}

因为要集成spring,所以该类加了注解@Component,以便执行时能自动扫描到。

因为集成了spring,所以需要的userService可以通过注解@Autowired自动获取到。


3、测试主类

public class SpringTestRunner extends JUnitStories {

    private ApplicationContext context;

    public SpringTestRunner() {
    }

    @Override
    public Configuration configuration() {
        return new MostUsefulConfiguration()
                .useStoryParser(new RegexStoryParser(new ExamplesTableFactory(new LoadFromClasspath(this.getClass()))))
                .useStoryReporterBuilder(new StoryReporterBuilder().withRelativeDirectory("doc/jbehave")
                        .withCodeLocation(CodeLocations.codeLocationFromClass(getClass())).withDefaultFormats()
                        .withFormats(CONSOLE, TXT, HTML, XML));
    }

    @Override
    protected List<String> storyPaths() {
        List<String> result = new StoryFinder().findPaths(CodeLocations.codeLocationFromClass(this.getClass()), "**/*.story", "");
        System.out.println("storyPaths:" + result);
        return result;
    }


    public InjectableStepsFactory stepsFactory() {
        return new SpringStepsFactory(configuration(), context());
    }

    private ApplicationContext context() {
        if (context == null) {
            context = new SpringApplicationContextFactory("v3-market.xml").createApplicationContext();
        }
        return context;
    }
}

因为是要执行所有的story测试,所以该类扩展了JUnitStories,并重写了storyPaths 方法,根据自己的情况发现并加载相应的story文件。


4、执行

JUnitStories有一个注解为@Test的run(),所以SpringTestRunner是可以直接执行的junit类,通过执行该类,将会扫描所有的story并进行相应的测试,最后生成测试报告。


5、测试报告

生成报告文件列表如下,主要的测试通过view中的index.html查看。

【JBehave】集成spring测试_第1张图片

详细的测试结果,因为没有将jbehave-site-resources和jbehave-core-resources.zip中的内容解压到view目录下,所有看到的测试报告页面有点丑。

【JBehave】集成spring测试_第2张图片

你可能感兴趣的:(spring,测试,jbehave,bdd)