单元测试
开发中,每当完成一个功能接口或业务方法的编写后,通常都会借助单元测试验证该功能是否正确。 Spring Boot对项目的单元测试提供了很好的支持,在使用时,需要提前在项目的pom.xml文件中添加 spring-boot-starter-test测试依赖启动器,可以通过相关注解实现单元测试
演示:
- 添加spring-boot-starter-test测试依赖启动器
在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,示例代码如下:
org.springframework.boot
spring-boot-starter-test
test
注意:使用Spring Initializr方式搭建的Spring Boot项目,会自动加入spring-boot-starter-test测试依赖 启动器,无需再手动添加
- 编写单元测试类和测试方法
使用Spring Initializr方式搭建的Spring Boot项目,会在src.test.java测试目录下自动创建与项目主程序 启动类对应的单元测试类
@RunWith(SpringRunner .class) // 测试启动器,并加载 Spring Boot 测试注解
@SpringBootTest //标记为Spring Boot单元测试类,并加载项目的Applicationcontext上下 文环境
class SpringbootDemoApplicationTests {
@Autowired
private DemoController demoController;
//自动创建的单元测试方法实例
@Test
void contextLoads() {
String demo = demoController.demo();
System.out.println(demo);
}
}
上述代码中,先使用@Autowired注解注入了 DemoController实例对象,然后在contextLoads()方法中 调用了DemoController类中对应的请求控制方法contextLoads(),并输出打印结果
![fa21a171dca3f160d12703ff05303aec.png](https://i-blog.csdnimg.cn/blog_migrate/5210a8cd8f2a13ca75881658398a5b8b.jpeg)
打印结果