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

代码承接上一篇博文——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容器,整合后使用测试类时必须存在

猜你喜欢

转载自blog.csdn.net/m0_37673753/article/details/79299615