搞定!SpringBoot单元测试的详细指南
最编程
2024-08-05 19:21:44
...
本文介绍了详解SpringBoot之添加单元测试,分享给大家,希望此文章对各位有所帮助
在SpringBoot里添加单元测试是非常简单的一件事,我们只需要添加SpringBoot单元测试的依赖jar,然后再添加两个注解就可搞定了。
首先我们来添加单元测试所需要的jar
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>
接着我们写了一个单元测试的demo
package com.zkn.learnspringboot.service.test; import com.zkn.learnspringboot.FirstExample; import com.zkn.learnspringboot.service.PersonService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by wb-zhangkenan on 2016/11/18. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FirstExample.class) public class TestService extends BaseTestService{ @Autowired private PersonService personService; @Test public void testSys() { System.out.println(personService.getPersonDomain().toString()); } }
然后我们run一下,一个单元测试就搞定了。
另外:@RunWith和@SprintBootTest这两个注解上都有@Inherited这个注解,所以我们可以定义一个单元测的父类,然后所有的单元测试类继承这个父类就行了。如下所示:
package com.zkn.learnspringboot.service.test; import com.zkn.learnspringboot.FirstExample; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by zkn on 2016/11/20. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = FirstExample.class) public class BaseTestService { }
package com.zkn.learnspringboot.service.test; import com.zkn.learnspringboot.service.PersonService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Created by wb-zhangkenan on 2016/11/18. */ public class TestService extends BaseTestService{ @Autowired private PersonService personService; @Test public void testSys() { System.out.println(personService.getPersonDomain().toString()); } }
如果你用的SpringBoot是1.4.0之前的话,所用的注解稍有不同。你需要把@SpringBootTest注解换成@SpringApplicationConfiguration和@WebAppConfiguration。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
-
SpringBoot 驱动的高校学科竞赛平台开发指南
-
基于 SpringBoot+Vue+uniapp 微信小程序的婚纱摄影小程序的详细设计与实现(源代码+lw+部署文档+说明等)
-
基于 SpringBoot+Vue+uniapp 的在线招聘平台的详细设计与实施
-
基于 SpringBoot+Vue+uniapp 的诗歌学习系统的详细设计与实现
-
基于 SpringBoot+Vue+uniapp 的诗歌学习系统的详细设计与实施(源代码+lw+部署文档+说明等)
-
处理外部安全反馈的完整安全工程师指南 - 2.详细分析
-
后端 Java-SpringBoot 集成 MyBatisPlus 的步骤(超级详细)
-
在 Momentum Cloud 中使用 Llama-3.2-11B-Vision 的详细指南
-
如何在Ubuntu系统中进行详细的Zip文件解压缩指南
-
ML之sklearn:学习sklearn.linear_model中的LogisticRegression函数的详细介绍与使用指南(一)