单元测试代码
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath*:spring/*.xml" }) public class UserTest { @Autowired UserService userService; @Test public void testUser(){ System.out.println("单元测试"); //查询一个用户信息 UserVo user = userService.getUser(1); System.out.println(user.getName()); } }
运行报错:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0’: Invocation of init method failed; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [WEB-INF/css/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@557a1e2d]]] does not run in a WebApplicationContext but in: org.springframework.context.support.GenericApplicationContext@62ee68d8: startup date [Sun Jul 30 18:48:01 CST 2017]; root of context hierarchy
错误提示静态资源css创建有问题,静态资源Handler的ResourceHttpRequestHandler不能创建
解决:添加注解@WebAppConfiguration(“src/main/resources”)
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("src/main/resources") @ContextConfiguration(locations = { "classpath*:spring/*.xml" }) public class UserTest { @Autowired UserService userService; @Test public void testUser(){ System.out.println("单元测试"); //查询一个用户信息 UserVo user = userService.getUser(1); System.out.println(user.getName()); } }
这个注解的作用就是指定到配置文件的根路径
@WebAppConfiguration is a class-level annotation that is used to declare that the ApplicationContext loaded for an integration test should be a WebApplicationContext. The presence of @WebAppConfiguration on a test class indicates that a WebApplicationContext should be loaded for the test using a default for the path to the root of the web application. To override the default, specify an explicit resource path via the value() attribute. Note that @WebAppConfiguration must be used in conjunction with @ContextConfiguration, either within a single test class or within a test class hierarchy. @WebAppConfiguration是一个类级别的注释,用于声明ApplicationContext为集成测试加载的应该是a WebApplicationContext。 @WebAppConfiguration测试类的存在表明WebApplicationContext应该使用Web应用程序根路径的默认值为测试加载a。要覆盖默认值,请通过该value()属性指定显式资源路径。 请注意,@WebAppConfiguration必须与 @ContextConfiguration单个测试类或测试类层次结构一起使用。 从Spring Framework 4.0开始,此批注可用作 元注释来创建自定义组合注释。
