SpringBoot基础回顾

6次阅读

共计 1138 个字符,预计需要花费 3 分钟才能阅读完成。

1.4 单元测试与热部署

(1)单元测试

​ 开发中,每当完成一个功能接口或业务方法的编写后,通常都会借助单元测试验证该功能是否正确。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 工程师高薪训练营》里学到的,课程内容非常全面,还有拉勾的内推大厂服务,推荐你也看看。

正文完
 0