单元测试与热部署

 开发中,每当完成一个功能接口或业务方法的编写后,通常都会借助单元测试验证该功能是否正确。Spring Boot对项目的单元测试提供了很好的支持,在使用时,需要提前在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,可以通过相关注解实现单元测试

 

演示:

 

1.添加spring-boot-starter-test测试依赖启动器

 

在项目的pom.xml文件中添加spring-boot-starter-test测试依赖启动器,示例代码如下 :

 

```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工程师高薪训练营》,看到刚学到的点就回答了。希望拉勾能给我推到想去的公司,目标:字节!!
posted @ 2020-06-05 15:26  西西宝贝  阅读(43)  评论(0)    收藏  举报