赞
踩
使用SpringBoot 测试类可在不需要启动程序时,即可使用。当你运行你的测试方法时他会自己启动程序调用所需使用到的mapper,service接口,实现方法。故而可在测试类中像编写正常service方法一样编写代码
<!--Spring Boot 测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
import com.sinosoft.springbootplus.AccidentApplication; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest(classes = Application.class) @RunWith(SpringRunner.class) @Slf4j public class test { @Autowired XXXService xxxService; @Test public void testDemo() { // ... } }
在这里讲解下几个注解的作用及流程
1.@SpringBootTest(classes = 启动类名称.class)
基本等同于启动了整个服务,此时便可以开始功能测试。
注:
1)如果注解@SpringBootTest(classes = 启动类名称.class)中配置了项目启动类,则该测试类可以放在test.java下任何包中
2)如果注解@SpringBootTest没有配置里面的参数classes = Application.class,则需要确保test.java下的测试类包与启动类所在的包一致,即在test.java下也需要创建com.xunan.demo包,并将测试类放在该包下。
不然会报 Unable to find a @SpringBootConfiguration, you need to use @ContextConfigura错误
2.运行器指定@RunWith
在JUnit中有很多个Runner,他们负责调用你的测试代码,每一个Runner都有各自的特殊功能,你要根据需要选择不同的Runner来运行你的测试代码。一般使用@RunWith(SpringRunner.class)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。