@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {com.yves.service.DemoService.class}) @DirtiesContext public class DemoServiceTest {
@Autowired private DemoService demoService;
@Test public void testPrintName() { demoService.printName(); } }
在 @ContextConfiguration 注解中,需要传入一个 ClassLoader 和待测试的类,所以我们也可以简单推测下:通过这样的注解,Junit 可以通过加载指定的 Class 文件,帮我们完成注入。
@DirtiesContext 注解表明底层 Spring 容器在该方法的执行中被“污染”,从而必须在方法执行结束后重新创建(无论该测试是否通过)。
顺便提一句:@ContextConfiguration 里还有一个 locations 属性,我们可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件。如下所示: @ContextConfiguration(locations={“xx/beans1.xml”,” yy/beans2.xml”})