springboot 集成测试

本文详细介绍了如何在SpringBoot项目中进行单元测试,包括引入Maven依赖、使用JUnit注解进行测试方法的编写,以及@Before、@After等注解的作用和使用场景。并通过示例代码展示了测试方法的执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot 的测试,在Junit的基础上进行封装,首要是引入maven 依赖

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

其次,在src/test/java/xxxpackage/xxxApplicationTest.java中,创建测试文件,使用junit 注解即可,熟悉junit测试的下面可以忽略。

junit 注解常见的有 @Test @Before @After,@Test可以指定超时时间timeout 及异常,来验证测试case的性能或者异常,除此之外,@BeforeClass @AfterClass 的用途也会在下面的示例中的注释中一一说明

@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceApplicationTests {



    /**
     * 启动的过程中输出beforeClass serviceImpl ,适用于全局的统一处理
     *
     * Method beforeClass() should be static
     *
     * 2019-08-20 14:56:12,702 INFO (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.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]
     * 2019-08-20 14:56:12,722 INFO (AbstractTestContextBootstrapper.java:177)- Using TestExecutionListeners:
     *      [org.springframework.test.context.web.ServletTestExecutionListener@55536d9e,
     *      org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@747edf66,
     *      org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@3d1cfad4,
     *      org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@62230c58,
     *      org.springframework.test.context.support.DirtiesContextTestExecutionListener@2cd2a21f,
     *      org.springframework.test.context.transaction.TransactionalTestExecutionListener@2e55dd0c,
     *      org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@74455848,
     *      org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@e7edb54,
     *      org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@378542de,
     *      org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@3738449f,
     *      org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@69e1dd28,
     *      org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@11bd0f3b]
     *
     *      beforeClass serviceImpl   (--启动的过程中输出beforeClass serviceImpl)
     */
    @BeforeClass
    public static void beforeClass(){
        System.out.println("beforeClass serviceImpl");
    }


    /**
     * 在每个测试方法前执行
     * 一般用于初始化方法
     */
    @Before
    public void before(){
        System.out.println("before serviceImpl");
    }


    /**
     * 忽略执行的方法
     * Ignore value: 忽略执行该测试方法时,会同时输出value值,以作忽略说明
     */
    @Ignore(value = "忽略执行的测试case")
    @Test
    public void ignore(){
        System.out.println("ignore Test serviceImpl");
    }

    /**
     * 正常的测试方法
     */
    @Test
    public void contextLoads() {
        System.out.println("test serviceImpl");
    }

    /**
     * timeout = 1000L: 测试方法执行超过1000毫秒后算超时,测试将失败
     * expected = Exception.class: 测试方法期望得到的异常类,如果方法执行没有抛出指定的异常,则测试失败
     *
     * java.lang.Exception: Unexpected exception, expected<java.lang.Exception> but was<java.lang.Error>
     * Caused by: java.lang.Error: 这是一个错误
     */
    @Test(timeout = 1000L,expected = Exception.class )
    public void testTimeoutAndExpected(){
        System.out.println("测试异常和超时");
        throw new Error("这是一个错误");
        //throw new RuntimeException("这是一个异常");
    }

    /**
     * 在test 执行完后要做的事情
     */
    @After
    public void after(){
        System.out.println("after serviceImpl");
    }

    /**
     * java.lang.Exception: Method afterClass() should be static
     *
     * @Before @Test @After 全部执行完之后,开始执行
     */
    @AfterClass
    public static void afterClass(){
        System.out.println("afterClass serviceImpl");
    }
}


//输出顺序:
beforeClass serviceImpl
忽略执行的测试case
。。。。(启动过程)
。。。。。(启动过程)
before serviceImpl
测试异常和超时
after serviceImpl

java.lang.Exception: Unexpected exception, expected<java.lang.Exception> but was<java.lang.Error>

	at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
	at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298)
	at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.Error: 这是一个异常
	at com.cutiyu.promotion.serviceimpl.PromotionServiceApplicationTests.testTimeoutAndExpected(PromotionServiceApplicationTests.java:98)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
	at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
	at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
	... 9 more

before serviceImpl
test serviceImpl
after serviceImpl
afterClass serviceImpl



//若修改testTimeoutAndExpected 抛出RuntimeException,则输出顺序如下:
beforeClass serviceImpl
忽略执行的测试case
。。。。(启动过程)
。。。。。(启动过程)
before serviceImpl
测试异常和超时
after serviceImpl
before serviceImpl
test serviceImpl
after serviceImpl
afterClass serviceImpl

通过输出结果可知,@Before和@After 会在每个@Test 注解执行之前和之后,分别执行一次。

@BeforClass 和@AfterClass 全局只执行一次
 

在Spring Boot中,集成测试是用来测试整个应用程序或特定模块与外部依赖的交互是否正常的测试。集成测试可以确保不同组件之间的协作正常,并验证其与外部服务或数据库的交互是否正确。与单元测试不同,集成测试涉及多个组件的协同工作,它们可能包括数据库、消息队列、外部API等。 在新版的Spring Boot中,不再需要使用@ExtendWith注解来表明Spring环境,因为它已经作为元注解嵌入在集成测试注解中,例如@SpringBootTest和@WebMvcTest。通过使用这些注解,我们可以轻松地进行Spring Boot的集成测试。@SpringBootTest注解会加载所有被Spring容器管理的bean,而@WebMvcTest注解只会加载指定的bean,例如@WebMvcTest(UserController.class)只会加载UserController类。 总的来说,Spring Boot集成测试是用来验证应用程序各个组件之间的协作是否正常,并确保与外部依赖的交互是否正确。通过使用适当的注解,我们可以轻松地进行集成测试,而无需过多的配置和额外的代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【开发技术】springboot自动化测试 【单元测试、集成测试】](https://blog.youkuaiyun.com/a23452/article/details/126019951)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [SpringBoot集成测试](https://blog.youkuaiyun.com/qq1137623160/article/details/106709582)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值