Spring整合Junit
在之前文章中Spring的测试方法几乎都能够看到如下的代码:
ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml");
XXX xxx = context.getBean(XXX.class);
它的作用是创建Spring容器,最终获取到对象,但是在每次测试时都需要重复编写。造成代码冗余。可以通过Spring整合JUnit可以使程序创建spring容器。
步骤
1、引入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>6.0.9</version>
</dependency>
<!---aspects是spring aop事务管理的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>6.0.9</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.0-M1</version>
<scope>test</scope>
</dependency>
<!-- spring整合junit相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
2、bean.xml
<?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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="com.louis.junitTest"></context:component-scan>
</beans>
3、创建目标类
@Component
public class User {
public void user(){
System.out.println("User.....");
}
}
4、创建测试类
①JUnit5
方式一
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean.xml")
方式二
@SpringJUnitConfig(locations = "classpath:bean.xml")
public class TestUser {
//注入
@Autowired
private User users;
@Test
public void test(){
users.user();
}
}
/*
* User.....
*/
②JUnit4
依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
整合JUnit4
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class TestJUnit {
//注入User
@Autowired
private User user;
@Test
public void testUser(){
user.user();
}
}
/*
* User.....
* */