学科分类
目录
Spring Boot开发

单元测试

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

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

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

上述代码中,展示了Spring Boot框架集成单元测试提供的依赖启动器,其<scope>范围默认为test。需要说明的是,如果是使用Spring Initializr方式搭建的Spring Boot项目,会自动加入spring-boot-starter-test测试依赖启动器,无需开发者再手动添加。

2.编写单元测试类和测试方法

在项目中添加测试依赖启动器后,可以编写Spring Boot项目中相关方法对应的单元测试。如果是使用Spring Initializr方式搭建的Spring Boot项目,会在src.test.java测试目录下自动创建与项目主程序启动类对应的单元测试类。例如,chapter01项目的Chapter01ApplicationTests是自动生成的单元测试类,内容如文件1所示。

文件1 Chapter01ApplicationTests.java

 1    import org.junit.Test;
 2    import org.junit.runner.RunWith;
 3    import org.springframework.boot.test.context.SpringBootTest;
 4    import org.springframework.test.context.junit4.SpringRunner;
 5    /**
 6     * 使用Spring Initializr方式自动创建的主程序启动类对应的单元测试类
 7     */
 8    @RunWith(SpringRunner.class) // 测试启动器,并加载Spring Boot测试注解
 9    @SpringBootTest  // 标记为Spring Boot单元测试类,并加载项目的ApplicationContext上下文环境
 10    public class Chapter01ApplicationTests {
 11        // 自动创建的单元测试方法示例
 12        @Test
 13        public void contextLoads() {
 14        }
 15    }

文件1中,Chapter01ApplicationTests是chapter01项目主程序启动类对应的单元测试类,该类自动生成了一个单元测试方法的示例。第9行代码的@SpringBootTest注解用于标记该类为测试类,并加载项目的ApplicationContext上下文环境;第8行代码的@RunWith注解是一个测试类运行器,用于加载Spring Boot测试注解@SpringBootTest。

下面,在单元测试类Chapter01ApplicationTests中添加HelloController类中hello()请求控制方法对应的单元测试方法,示例代码如下。

@Autowired
private HelloController helloController;
@Test
public void helloControllerTest() {
    String hello = helloController.hello();
    System.out.println(hello);
}

上述代码中,先使用@Autowired注解注入了HelloController实例对象,然后在helloControllerTest()方法中调用了HelloController类中对应的请求控制方法hello(),并输出打印结果。

选中单元测试方法helloControllerTest(),鼠标右键单击“Run ‘helloControllerTest()’”选项启动测试方法,此时控制台的打印信息如图1所示。

图1 helloControllerTest()单元测试方法效果

从图1可以看出,控制台打印出了“hello Spring Boot”信息,说明了控制类HelloController中编写的hello()方法正确,并且单元测试方法执行成功。

点击此处
隐藏目录