SpringMVC 单元测试

参考链接:https://blog.csdn.net/bestfeng1020/article/details/70145433

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

Demo如下:

@RunWIth(SpringJunit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"}
public  class MyTest{ @Test public 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” })

猜你喜欢

转载自www.cnblogs.com/txfsheng/p/9071408.html