打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
spring-boot(十二)单元测试

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

还是看下官方文档说明:

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

目录结构图

一. 引入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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
小白搞 Spring Boot单元测试
spring-boot 1.4单元测试及1.3配置的区别
Spring Boot 引入自定义yml
Spring Boot 集成 JUnit5,更优雅单元测试!
从零开始 -Spring Boot 2单元测试与集成测试知识点全了-知识铺
java的单元测试和集成spring单元测试
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服