Spring集成Junit步骤
- 导入spring集成Junit的坐标
(spring-test)
- 使用@Runwith注解替换原来的运行期
(@RunWith(SpringJUnit4ClassRunner.class))
- 使用@ContextConfiguration指定配置文件
@ContextConfiguration(“classpath:application.xml”)
@ContextConfiguration(classes = SpringConfiguration.class)
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
集成前,进行测试:
@Test
//测试scope属性---userDao_singleton
public void test1(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");//创建容器
UserDao userDao1 = (UserDao) app.getBean("userDao_singleton");
UserDao userDao2 = (UserDao) app.getBean("userDao_singleton");
System.out.println(userDao1);
System.out.println(userDao2);
}
集成后:
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:application.xml")
@ContextConfiguration(classes = SpringConfiguration.class)
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}