Spring 3.0的测试框架可以和Junit4 整合, 通过Junit4的@RunWith注解指定SpringJunit4ClassRunner.class 的测试运行器,该运行器是spring 提供的,可以将Spring容器和Junit4测试框架整合。@ContextConfiguration也是Spring提供的,用于指定Spring的配置文件。
在测试类中可以使用spring的@Autowired将Spring容器中的Bean注入到测试类中来。在测试方法通过Junit4的@Test注解即可将方法标注为测试方法。看下面的例子:
@RunWith(SpringJUnit4ClassRunner.class)//基于Junit4的Spring测试框架
@ContextConfiguration(location={"/applicationContext.xml"})//启动Spring容器
public class TestUserService{
//注入Spring容器中的bean
@AutoWired
private UserService userService;
@Test
public void hasMatchUser(){
boolean b1 = userService.hasMatchUser("admin","123456");
boolean b2 = userSerive.hasMatchUser("admin","11111");
}
...
}
//<span style="font-family: Arial, Helvetica, sans-serif;">在MyEclipse中,通过Run As -> JUnit Test 运行该测试用例以检验业务类方法的正确性。</span><pre name="code" class="java">