1、在pom文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、约定写法
单元测试代码写在src/test/java目录下。
单元测试类命名为*Test,前缀为要测试的类名。
3、@SpringBootTest注解的作用
-
@SpringBootTest替代了spring-test中的@ContextConfiguration注解,目的是加载ApplicationContext,启动spring容器。
-
使用@SpringBootTest时并没有像@ContextConfiguration一样显示指定locations或classes属性,原因在于@SpringBootTest注解会自动检索程序的配置文件,检索顺序是从当前包开始,逐级向上查找被@SpringBootApplication或@SpringBootConfiguration注解的类。
4、Service测试
对于service层的测试比较简单,直接自动注入就可以测试:
service:
@Service
public class HelloService {
public String sayHello(){
return "hello service";
}
}
测试类:
@SpringBootTest
class DevtoolsApplicationTests {
@Autowired
HelloService helloService;
@Test
void test() {
String str = helloService.sayHello();
System.out.println(str);
}
}
5、Controller及Json测试
在Springboot中对Controller和Json测试比较不常用,也比较麻烦,一般我们使用浏览器和Postman进行测试非常方便,这里就不赘述了,百度一下吧。