您的位置:首页 > 编程语言 > Java开发

Spring的基础学习(十二)——Spring与Junit的整合

2018-02-09 16:17 405 查看
代码承接上一篇博文——spring的事务管理

    不得不说,Spring与Junit的整合十分简便,用起来让人感觉很舒服。在开发过程中做测试时推荐常用,尤其是对dao层的测试。

首先,pron.xml添加如下代码,导入Junit与spring的整合包<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
<scope>test</scope>
</dependency>对测试类的修改:@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestApp {

@Autowired //与junit整合,不需要在spring xml配置扫描
private AccountService accountService;

@Test
public void demo01(){
// String xmlPath = "applicationContext.xml";
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
// AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("jack", "rose", 1000);
}

}
注意测试类的代码@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations="classpath:applicationContext.xml")
这两个注释会初始化我们的Spring容器,整合后使用测试类时必须存在
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: