- 安装spring-test和junit依赖,其中junit依赖的版本不低于4.12
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
- 给测试类增加注解
- @RunWith(SpringJUnit4ClassRunner.class) 修改JUnit的main方法
- @ContextConfiguration() 通过locations属性指定XML配置文件或通过classess属性指定配置类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class RoleServiceTest {
@Autowired
private RoleService roleService;
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:Beans.xml"})
public class RoleServiceTest {
@Autowired
private RoleService roleService;
}