栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Junit5集成到SpringBoot工程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Junit5集成到SpringBoot工程

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的依赖:


    org.springframework.boot
    spring-boot-starter-test
    test
    
        
            org.junit.vintage
            junit-vintage-engine
        
    

如果仅使用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:CodeLearntest-utiljunitjunit5-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 GuideJunit5 GithubJUnit 5 测试 Spring 引擎的时候提示 junit-vintage 错误springboot常用starter⑬-spring-boot-starter-test

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/272429.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号