我正在对我的Spring网络应用进行集成测试,需要验证生成的HTML网页。 我正在测试完整的Web应用程序上下文,但自定义视图解析器(JTwig)存在问题。这是我的代码:
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Config.class})
@WebAppConfiguration
public class FrontControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
WebApplicationContext wac;
@InjectMocks
private FrontController frontController = new FrontController();
@Before
public void setup() throws JAXBException, XMLStreamException {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void mainSearchPage() throws Exception {
mockMvc.perform(get("/search/ww/en/altivar"))
.andExpect(status().isOk())
.andExpect(view().name("searchResults"))
.andExpect(model().attribute("idolResponse", isA(SearchResults.class)))
.andExpect(model().attribute("numberOfPages", is(188)))
.andExpect(model().attribute("stateId", isNull()));
}
}
自定义视图解析器:
public class Config extends WebMvcConfigurerAdapter implements WebApplicationInitializer {
...
@Bean
public ViewResolver viewResolver() {
JtwigViewResolver view = new JtwigViewResolver();
view.setPrefix("/WEB-INF/templates/");
view.setSuffix(".twig");
return view;
}
测试失败,错误:
Caused by: com.lyncode.jtwig.exception.ResourceException: Resource /WEB-INF/templates/searchResults.twig not found
at com.lyncode.jtwig.resource.WebJtwigResource.retrieve(WebJtwigResource.java:36)
at com.lyncode.jtwig.parser.parboiled.JtwigContentParser.parse(JtwigContentParser.java:62)
... 54 more
经过多次挖掘后,我知道抛出异常的地方:
@Override
public InputStream retrieve() throws ResourceException {
InputStream resourceAsStream = servletContext.getResourceAsStream(url);
if (resourceAsStream == null) throw new ResourceException("Resource "+url+" not found");
return resourceAsStream;
}
servletContext
为org.springframework.mock.web.MockServletContext
答案 0 :(得分:0)
您的资源可能不是从主要资源中复制的。 dir to' test'。尝试运行测试并转到$ PROJECT_HOME / target / $ PROJECT_NAME - 是WEB_INF文件夹,其中有模板(如果是maven项目,我不确定gradle是否使用相同的结构)?
如果它们不存在那么你可能必须在pom.xml中定义节点。看看文档: http://maven.apache.org/plugins/maven-resources-plugin/testResources-mojo.html
答案 1 :(得分:0)
请注意,默认情况下,注释@WebAppConfiguration假定执行目录是项目的目录,并且它遵循默认的maven结构。
如果您在某些IDE上运行测试,则可能不符合此要求。此外,如果您的项目不遵循默认的maven结构,则您需要在注释中传递webapp目录位置。
查看文档:{{3}}