1。。引入spring-test依赖(或添加jar包):
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.18.RELEASE</version>
<scope>test</scope>
</dependency>
2。。使用junit提供的@RunWith
把原有的main函数替换为spring提供的
3。。使用spring提供的@ContextConfiguration
告知spring,配置文件或者注解类所在的位置,用于加载容器
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-config.xml")
public class UserServiceImplTest {
@Autowired
UserService userService;
@Test
public void addUser() {
userService.addUser();
}
}