Spring Web 项目Junit测试报错问题

测试对象是Web项目的Service类,参照网上查到的资料,按如下方式执行时报错,

//使用junit4进行单元测试
@RunWith(SpringJUnit4ClassRunner.class)
//加载配置文件,可以指定多个配置文件,locations指定的是一个数组
@ContextConfiguration(locations={"classpath:spring/applicationContext-*.xml", "classpath:spring/springmvc.xml"})
//启动事务控制
@Transactional
//配置事务管理器,同时指定自动回滚
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
public class BaseJunit4Test {
    //进行测试时,将测试类继承该类
    //注入service对象
    //然后在方法上使用@Test,@RollBack,@Transaction等注解单独修饰
}

执行后报错如下:

  Caused by java.lang.IllegalStateException:WebApplicationObjectSupport instance[ResourceHttpRequestHandler [locations=[class path resource [assert/]],resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@...]]] does not run in a WebApplicationContext but in : org.springframework.context.support.GenericAppliactionContext............

网上找到了类似的问题,说是在配置文件中将assert相关的静态资源目录去掉就可以了。感觉不靠谱,因为工程在tomcat中启动是没有什么问题的。

刚开始用Junit,不太熟悉,后来想,可能是Junit配置没有支持Web工程。然后又搜索怎么对Controller层进行单元测试的,结果发现了测试类上面的@WebAppConfiguration注解。猜想正是因为少了这个注解的问题。

于是在测试代码中加上了这个注解,就不报错了。

Junit很强大,还是要好好学习一下的。

遇到问题,在此Mark一下。这是我的错题集。

原文地址:https://www.cnblogs.com/aligege/p/8630555.html