单元测试是软件开发中非常重要的一环,通过编写和运行单元测试,开发者可以确保代码在各个模块的功能是正确的。本文将介绍如何在SpringBoot中进行单元测试,包括常见的测试工具和最佳实践。
SpringBoot默认集成了JUnit5进行单元测试。
以基于Maven的工程为例,使用SpringBoot Initializr创建的项目通常默认已经引入了单元测试的起步依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
基于Maven的项目结构,我们在src/test/java
下可以创建单元测试类,下面是一个例子。
package com.gacfox.demo;
import com.gacfox.demo.service.DemoService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
class DemobootApplicationTests {
@Resource
private DemoService demoService;
@Test
void testDemoService() {
int result = demoService.demo();
Assertions.assertEquals(1, result);
}
}
代码中,单元测试类通常以XXXTests
命名,而测试方法则通常以testXXX()
命名。我们使用@SpringBootTest
标注了单元测试类,这样我们就能在单元测试中正常使用Spring的依赖注入了,其他用法与JUnit的基础使用方式一致。
在实际开发中,服务类可能会依赖其他类或组件,这时一种常见的做法是使用Mockito来模拟这些依赖。
首先我们需要引入Mockito框架。
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
下面例子我们使用Mockito模拟了一个远程服务接口并调用。
package com.gacfox.demo;
import com.gacfox.demo.model.User;
import com.gacfox.demo.service.RemoteServiceApi;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
@SpringBootTest
class DemobootApplicationTests {
@MockBean
private RemoteServiceApi remoteServiceApi;
@Test
void testDemoService() {
Mockito.when(remoteServiceApi.getUser("1")).thenReturn(new User("1", "张三"));
User user = remoteServiceApi.getUser("1");
Assertions.assertEquals("张三", user.getName());
}
}
代码中,我们使用了@MockBean
注解,它会自动创建一个Mock对象并替换Spring容器中的原对象并将其注入到单元测试中。在测试方法内,我们使用了Mockito.when().thenReturn()
的写法来模拟远程服务的返回结果,最后调用远程服务并验证。