用Spring管理的项目,在不启动服务的情况下进行测试类测试:@RunWith @ContextConfiguration

来源:互联网 发布:语玩刷金币软件下载 编辑:程序博客网 时间:2024/06/07 09:55

Demo如下:

@RunWIth(SpringJunit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:applicationContext.xml"}public  class MyTest{@Testpublic void runBy(){//.......}}

Spring常用的 Bean对象 如Service Dao Action等等 在我们正常的项目运行中由于有Tomcat帮我们自动获得并初始化了这些Bean,所以我们不需要关系如何手动初始化他们。
但是在需要有测试类的时候,是没有tomcat帮我们初始化它们的,这时候如果是下面这样就抛出空指针异常,因为我们并没有得到一个实例化的Bean

public  class MyTest{ @Resource private StudentService  studentService  ;    @Test    public void runBy(){    //抛出空指针异常。这里的studentService  为空,并没有被初始化Bean对象        studentService.study();    }}

所以这里需要加上@RunWith @ContextConfiguration这两个注解

@RunWith

@RunWith就是一个运行器
@RunWith(JUnit4.class)就是指用JUnit4来运行
@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境

@ContextConfiguration

@ContextConfiguration Spring整合JUnit4测试时,使用注解引入多个配置文件

单个文件
@ContextConfiguration(Locations=”../applicationContext.xml”)
@ContextConfiguration(classes = SimpleConfiguration.class)

多个文件时,可用{}
@ContextConfiguration(locations = { “classpath*:/spring1.xml”, “classpath*:/spring2.xml” })

1 0
原创粉丝点击