Spring 整合 Junit 的配置过程:
1、导入 Spring 整合 Junit 的 jar ( 坐标 )
2、使用 Junit 提供的一个注解把原有的 main 方法替换了,替换成 Spring 提供的
@Runwith
3、告知 Spring 的运行器, Spring 和 ioc 创建是基于 xml 还是注解的,并且说明位置,用到的注解如下
@ContextConfiguration
Locations : 指定 xml 文件的位置,加上 classpath 关键字,表示在类路径下(用xml配置时的引用)
classes : 指定注解类所在地位置(用注解配置时的引用)
4、使用@Autowired 给测试类中的变量注入数据
Maven的pom.xml中导入Junit的jar包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
使用xml配置Spring时实例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testTransfer(){
//编写调用的方法。
}
}
使用注解配置时的实例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testTransfer(){
as.transfer("aaa","bbb",100f);
}
}