1 导入相关坐标
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
2 使用@RunWith注解
@RunWith(SpringJUnit4ClassRunner.class)
3 使用@ContextConfiguration指定配置文件或配置类
@ContextConfiguration(“classpath:applicationContext.xml”)
4 使用@Autowired注入测试对象,@Test编写测试方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUserDao
{
@Autowired
private UserDao userDao;
@Test
public void testSaveUser()
{
userDao.saveUser();
}
}
*说明:如为无xml纯注解方式,可使用如下替换xml配置,SpringConfiguration为自定义Spring配置类
@ContextConfiguration(classes = {SpringConfiguration.class})