简介
Spring提供spring-test-5.2.1.RELEASE.jar 可以整合junit。
优势:可以简化测试代码(不需要手动创建上下文,即手动创建spring容器)
使用spring和junit集成的步骤
1.导入jar包
2.创建包com.igeek.test,创建类SpringTest
3.通过@Autowired注解,注入需要测试的对象
在这里注意两点:
举例说明一下
1.第一种:在applicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.igeek.service.impl.UserServiceImpl"></bean>
</beans>
public class UserServiceImpl implements IUserService {
@Override
public void save() {
System.out.println("save...");
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test01 {
@Autowired
private IUserService userService;
@Test
public void test01(){
userService.save();
}
}
2.第二种:在applicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.igeek"></context:component-scan>
</beans>
@Service("userService")
public class UserServiceImpl implements IUserService {
@Override
public void save() {
System.out.println("save...");
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test01 {
@Autowired
private IUserService userService;
@Test
public void test01(){
userService.save();
}
}