整合JUnit5
-
引入依赖
<!--spring对junit的支持相关依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>6.0.2</version> </dependency> <!--junit5测试--> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.9.0</version> </dependency> <!--1og4j2的依赖--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.19.0</version> </dependency>
-
创建spring配置类,开启组件扫描
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启组件扫描 --> <context:component-scan base-package="com.example"/> </beans>
-
创建User测试实体类
-
创建
SpringJUnit5
测试类package com.example; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @SpringJUnitConfig(locations = "classpath:bean.xml") public class SpringJUnit5 { //自动注入User类 @Autowired User user; //使用的是org.junit.jupiter.api.Test @Test public void UserTest() { //直接使用User实例 System.out.println(user); user.work(); } }
输出结果
com.example.User@4628b1d3
User work
另一个不常用的写法:
用@ExtendWith(SpringExtension.class) ‘ @ContextConfiguration("classpath:bean.xml")
代替
@SpringJUnitConfig(locations = "classpath:bean.xml")
整合JUnit4
-
额外添加依赖
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
-
创建
SpringJUnit4
测试类package com.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:bean.xml") public class SpringJUnit4 { @Autowired User user; //使用的是org.junit.Test @Test public void UserTest() { //直接使用User实例 System.out.println(user); user.work(); } }