标签: 测试

  • Spring Boot结合FluentLenium做集成测试

    对于Web应用,一般为了测试功能性,都会结合selenium做功能性测试。

    Selenium会启动浏览器访问网站,然后对网站进行交互性操作,并判断结果。

    一般的操作流程是,打war包,部署war包,等待Web应用启动,开始测试,整理测试结果,关闭Web应用。

    而Selenium只是一个测试工具,并不会管理其他问题,需要自己处理web应用的启动和关闭。

    同时Selenium暴露的API有些底层,对于WebDriver的管理需要自己控制,对于元素的查找等也比较繁碎。

    Spring Boot在1.2.X版本中增强了对于Integration测试的集成,当然也包括了WebIntegration的集成,可以使用这部分功能来管理除具体测试以外的管理问题,
    Spring Boot会在测试开始前启动Web应用,并在测试后关闭它们。

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = WebApplication.class)
    @WebIntegrationTest({"server.port=0","spring.profiles.active=test"})

    在测试类加上这段注解,server.port=0表示随机选取端口,而spring.profiles.active=test指定了当前profile为test。

    修改profile是很实用的,比如以我个人的习惯,我会在dev和prod中使用真实的数据库和其他组件,而在CI服务器上一般使用内存数据库,其他依赖组件尽可能使用内嵌式的,或者由docker提供,这样的话相关配置的区别就需要在不同的profile中区分了。

    随机化的端口可以保证测试不会由于端口占用失败,但是测试中我们需要用

    @Value("${local.server.port}")
    int port;

    把具体的端口号取到,以便在测试中使用。

    FluentLenium是一个写selenium测试的工具库,它可以帮你管理webdriver,并提供了更简单的API来加快测试的开发速度和可读性。

    FluentLenium默认使用的是Firefox Driver,可以自己修改。

    比如有一个测试去测试首页的标题

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = WebApplication.class)
    @WebIntegrationTest({"server.port=0","spring.profiles.active=test"})
    publicclass HomeTest extends FluentTest {
    @Value("${local.server.port}")
    int port;
    
    @Before
    publicvoidsetUp()throws Exception {
    goTo("http://localhost:" + port);
    }
    
    @Test
    publicvoidshouldEnableToSeeHomePage()throws Exception {
    assertThat(title(), containsString("ACG口琴网"));
    }
    }

    FluentLenium提供的API还有查找元素等等,基本上所有的功能都可以覆盖到

    await().atMost(3, TimeUnit.SECONDS).until("#searchForm").withText("关键字").isPresent();//等待搜索框弹出
    find(".list-group-item", withText("乐园の翼 full-size")).click();//点击带有指定文字的对象

    参考资料

    FluentLenium