1.4 单元测试与热部署java
(1)单元测试spring
开发中,每当完成一个功能接口或业务方法的编写后,一般都会借助单元测试验证该功能是否正确。Spring Boot对项目的单元测试提供了很好的支持,在使用时,须要提早在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,能够经过相关注解实现单元测试spring-boot
演示:单元测试
1.添加spring-boot-starter-test测试依赖启动器测试
在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,示例代码以下 :xml
xml对象
<dependency>接口
<groupId>org.springframework.boot</groupId>开发
<artifactId>spring-boot-starter-test</artifactId>部署
<scope>test</scope>
</dependency>
注意:使用Spring Initializr方式搭建的Spring Boot项目,会自动加入spring-boot-starter-test测试依赖启动器,无需再手动添加
2.编写单元测试类和测试方法
使用Spring Initializr方式搭建的Spring Boot项目,会在src.test.java测试目录下自动建立与项目主程序启动类对应的单元测试类
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(),并输出打印结果
<img src="./images/image-20191225135927575.png" alt="image-20191225135927575" style="zoom:67%;" />
这些内容,是从拉勾教育的《Java工程师高薪训练营》里学到的,课程内容很是全面,还有拉勾的内推大厂服务,推荐你也看看。