分享

spring-boot(十二)单元测试

 关平藏书 2018-01-12

spring-boot也为我们提供了便利的单元测试工具.
比如: MockMvc , TestRestTemplate
在项目开发中必须写单元测试,还是比较头疼的一件事.
其实我在项目中写单元测试并不是为了出一份测试报告,而是启动项目来调试时非常耗时的.
比如写好了一个数据库的sql,需要快速验证是否正确,如果没有单元测试,需要启动服务,打开浏览器,输入连接等等繁琐的步骤太影响开发效率了.

还是看下官方文档说明:
微信截图_20170302172417.png

微信截图_20170302172456.png

参照官网的介绍示例,直接拷贝就可以了
下面来介绍下单元测试开发步骤, 本案例代码在 spring-boot(二)数据库操作 基础上进行改造

目录结构图
微信截图_20170302172558.png

一. 引入test的pom插件支持

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>

二. 编写测试代码
service和dao层的测试

  1. package test;
  2. import ...
  3. //1.4.0版本之前写法
  4. //@RunWith(SpringJUnit4ClassRunner.class)
  5. //@SpringApplicationConfiguration(classes = MainApplication.class)
  6. //1.4.0版本之后写法
  7. @RunWith(SpringRunner.class)
  8. @AutoConfigureMockMvc
  9. @SpringBootTest(classes = MainApplication.class)
  10. public class ApplicationTests {
  11. @Autowired
  12. HelloService service;
  13. @Test
  14. public void test() {
  15. List<HelloBean> queryHellos = service.queryHellos();
  16. for (HelloBean helloBean : queryHellos) {
  17. System.out.println(helloBean);
  18. }
  19. }
  20. }

controller端的测试

  1. package hello;
  2. import ...
  3. @RunWith(SpringRunner.class)
  4. @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
  5. public class WebApplicationTests {
  6. @Autowired
  7. private TestRestTemplate restTemplate;
  8. @Test
  9. public void test() {
  10. String s = this.restTemplate.getForEntity("/hello/json", String.class, "jingjingMa").getBody();
  11. System.out.println(s);
  12. }
  13. }

源代码: my-springboot-12

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多