引言
由于spring boot在启动时通常会先行启动一些内置的组件,比如tomcat。因此,spring boot的测试类一般需要加一些简单的注解。
一、添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
二、测试类示例
@RunWith标记一个运行期SpringRunner.class(它是一个SpringJUnit4ClassRunner的子类,名字简短而已,未做任何扩展);
@SpringBootTest注解指定在测试类上用来运行基于Spring Boot的测试。
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {@Autowiredprivate UserService userService;@Beforepublic void setUp() throws Exception {// 启动时添加一些逻辑}/*** {"role":"teacher","teacherName":"王建国","jobTitle":"教授","gender":"男","username":"wangjianguo"}* <br>作者: mht<br> * 时间:2019年3月17日-下午10:47:07<br>*/@Testpublic void testAddOrUpdateUser() {JSONObject teacher = new JSONObject();teacher.put("role", "teacher");teacher.put("teacherName", "王力宏");teacher.put("jobTitle", "助理教授");teacher.put("gender", "男");teacher.put("username", "wanglihong");SystemResult addOrUpdateUser = userService.addOrUpdateUser(teacher);}
}
参考《Spring Boot干货系列:(十二)Spring Boot使用单元测试》