spring-boot也为我们提供了便利的单元测试工具. 比如: MockMvc , TestRestTemplate 在项目开发中必须写单元测试,还是比较头疼的一件事. 其实我在项目中写单元测试并不是为了出一份测试报告,而是启动项目来调试时非常耗时的. 比如写好了一个数据库的sql,需要快速验证是否正确,如果没有单元测试,需要启动服务,打开浏览器,输入连接等等繁琐的步骤太影响开发效率了.
还是看下官方文档说明:
参照官网的介绍示例,直接拷贝就可以了 下面来介绍下单元测试开发步骤, 本案例代码在 spring-boot(二)数据库操作 基础上进行改造
目录结构图
一. 引入test的pom插件支持
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
二. 编写测试代码 service和dao层的测试
package test;
import ...
//1.4.0版本之前写法 //@RunWith(SpringJUnit4ClassRunner.class) //@SpringApplicationConfiguration(classes = MainApplication.class)
//1.4.0版本之后写法 @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest(classes = MainApplication.class) public class ApplicationTests {
@Autowired HelloService service;
@Test public void test() { List<HelloBean> queryHellos = service.queryHellos(); for (HelloBean helloBean : queryHellos) { System.out.println(helloBean); } }
}
controller端的测试
package hello;
import ...
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class WebApplicationTests {
@Autowired private TestRestTemplate restTemplate;
@Test public void test() { String s = this.restTemplate.getForEntity("/hello/json", String.class, "jingjingMa").getBody(); System.out.println(s); }
}
源代码: my-springboot-12
|