【发布时间】:2014-10-14 11:24:18
【问题描述】:
我正在对我的 Spring Web 应用程序进行集成测试,并且需要验证生成的 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
【问题讨论】:
标签: java spring unit-testing spring-mvc integration-testing