Java程序员的日常—— Spring Boot单元测试

关于Spring boot

之前没有用Spring的时候是用的MockMvc,做接口层的测试,原理上就是加载applicationContext.xml文件,然后模拟启动各种mybatis\连接池等等。

后来web工程改造成了Spring boot,首先发生变化的就是配置文件,原来的xml改成了proerties或者yml。另外,原来的http接口改成了dubbo,接口层的测试就更困难了。

所以单元测试改成了直接对service层的测试,即按照原来的模式,模拟启动applicationContext,然后顺带启动其他的服务,获得service的bean,然后请求各种数据库。

总结起来发生变化的地方是:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class KJRecommendTest {

    @Autowired
    private MyService myService;

    @Test
    public void test(){
	    //assert
    }
}

这样就可以了。

关于单元测试

其实良好的单元测试应该想到各种复杂的情况,进行相应的测试,即做好各种边界的测试,这也是一个开发最基本考虑问题的因素。因此在开发编写单元测试时,有几个常用的方法可以使用:

assertEquals 是否相等

Assert.assertEquals(myService.query().size(),10);

assertThat 支持复杂点的比较

Assert.assertThat(list.size(), Matchers.allOf(Matchers.greaterThan(0), Matchers.lessThan(31)));

这个Matchers是引用org.hamcrest里面的,别引错啦

posted @ 2017-08-07 19:17  xingoo  阅读(881)  评论(1编辑  收藏  举报