1.说明
Spring Boot进行单元测试,
通过集成spring-boot-starter-test,
同时支持Junit4和Junit5测试框架,
下面使用Junit5进行单元测试,
基于一个已有的Spring Boot服务:
SpringBoot开发Restful接口
开发对应Restful接口的方法的单元测试。
区别于Junit4/5对于类级别的单元测试,
通过spring-boot-starter-test测试框架,
能够启动一个完全运行的web服务器,
同时监听自定义或随机端口模拟服务调用请求,
也可以使用Spring各种上下文和Bean实例,
进行服务器级别的单元测试。
2.引入Maven依赖
在pom.xml引入spring-boot-starter-test的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
如果仅使用Junit5,
不需要使用Junit4,
需要排除掉junit-vintage-engine依赖,
否则运行测试用例时可能会报错,
同时也能够避免Junit4和Junit5混用。
junit-vintage-engine是JUnit4的测试引擎。
junit-jupiter-engine是JUnit5的测试引擎。
3.新建测试类
在src/test/java目录下,
新建UserController的测试类UserControllerTest:
/**
* 用户的增删改查相关接口单元测试
*/
@SpringBootTest
public class UserControllerTest {}
注意在类名上面使用注解@SpringBootTest。
另外对于Junit4,
如果需要测试容器,
除了要加上@SpringBootTest,
还需要加上@RunWith(SpringRunner.class)
或者@RunWith(SpringJUnit4ClassRunner.class),
对于Junit5则不需要@RunWith。
4.新建测试方法
新建测试方法testGetOneUser(),
方法上面使用Junit5提供的注解@Test,
标识这是一个测试方法,
用于测试UserController的getOneUser的功能,
注意使用@Autowired注入UserController的实例,
这样在测试方法中就能调用相应的API,
而不会报空指针异常了。
完整的UserControllerTest.java:
package com.yuwen.spring.demo.controller;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.yuwen.spring.demo.entity.User;
@SpringBootTest
public class UserControllerTest {
@Autowired
UserController userController;
@Test
public void testGetOneUser() {
Long id = 90955L;
User oneUser = userController.getOneUser(id);
System.out.println(oneUser);
}
}
5.运行测试类
在Eclipse中运行测试类,
右键测试类UserControllerTest -> Run As -> Junit Test,
或者使用快捷键:
Alt + Shift + X, T
UserControllerTest单元测试执行结果如下:
17:37:22.939 [main] INFO [org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:308)] - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.yuwen.spring.demo.controller.UserControllerTest], using SpringBootContextLoader
17:37:22.947 [main] INFO [org.springframework.test.context.support.AbstractContextLoader.generateDefaultLocations(AbstractContextLoader.java:264)] - Could not detect default resource locations for test class [com.yuwen.spring.demo.controller.UserControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
17:37:22.948 [main] INFO [org.springframework.test.context.support.AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses(AnnotationConfigContextLoaderUtils.java:83)] - Could not detect default configuration classes for test class [com.yuwen.spring.demo.controller.UserControllerTest]: UserControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
17:37:23.042 [main] INFO [org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:237)] - Found @SpringBootConfiguration com.yuwen.spring.demo.DemoApplication for test class com.yuwen.spring.demo.controller.UserControllerTest
17:37:23.125 [main] INFO [org.springframework.test.context.support.AbstractTestContextBootstrapper.getDefaultTestExecutionListenerClassNames(AbstractTestContextBootstrapper.java:248)] - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
17:37:23.135 [main] INFO [org.springframework.test.context.support.AbstractTestContextBootstrapper.getTestExecutionListeners(AbstractTestContextBootstrapper.java:177)] - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@11f0a5a1, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@10f7f7de, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@73a8da0f, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@50dfbc58, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4416d64f, org.springframework.test.context.event.EventPublishingTestExecutionListener@6bf08014, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@5e3d57c7, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@732d0d24, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@1fb19a0, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@6ee4d9ab, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@5a5338df, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@418c5a9c]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.1.RELEASE)
17:37:23.465 [main] INFO [org.springframework.boot.StartupInfoLogger.logStarting(StartupInfoLogger.java:55)] - Starting UserControllerTest on yuwen-asiainfo with PID 17592 (started by yuwen in D:\Code\Learn\test-util\junit\junit5-springboot)
17:37:23.468 [main] INFO [org.springframework.boot.SpringApplication.logStartupProfileInfo(SpringApplication.java:651)] - No active profile set, falling back to default profiles: default
17:37:24.769 [main] INFO [org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.initialize(ExecutorConfigurationSupport.java:181)] - Initializing ExecutorService 'applicationTaskExecutor'
17:37:25.147 [main] INFO [org.springframework.boot.StartupInfoLogger.logStarted(StartupInfoLogger.java:61)] - Started UserControllerTest in 1.977 seconds (JVM running for 3.172)
getOneUser, id=90955
User [id=90955, name=null, birthday=null, email=null]
17:37:25.344 [SpringContextShutdownHook] INFO [org.springframework.scheduling.concurrent.ExecutorConfigurationSupport.shutdown(ExecutorConfigurationSupport.java:218)] - Shutting down ExecutorService 'applicationTaskExecutor'
可以看到启动了Spring Boot容器,
然后调用了UserController的getOneUser接口。
6.参考文章
Junit5集成到Maven工程
JUnit 5 User Guide
Junit5 Github
JUnit 5 测试 Spring 引擎的时候提示 junit-vintage 错误
springboot常用starter⑬-spring-boot-starter-test
网友评论