Spring5t整合JUnit5的单元测试

    技术2026-03-20  20

    Spring 5 全面接纳了函数式范例,并支持 JUnit 5 及其新的函数式测试风格。还提供了对 JUnit 4 的向后兼容性,以确保不会破坏旧代码。

    导入依赖:

    <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency>

    或者在程序中提示引入

    创建测试类,使用注解完成:

    @ExtendWith(SpringExtension.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestDemoJunit5 { @Autowired UserService userService; @Test public void test(){ userService.accountMoney(); } }

    或者使用一个复合注解替代上面两个注解完成整合

    @SpringJUnitConfig(locations = "classpath:applicationContext.xml") public class TestDemoJunit5 { @Autowired UserService userService; @Test public void test(){ userService.accountMoney(); } }
    Processed: 0.015, SQL: 10