繁体   English   中英

春季测试中缺少自定义视图解析器

[英]Custom view resolver missing in Spring test

我正在对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;
}

其中servletContextorg.springframework.mock.web.MockServletContext

您的资源可能没有从“主”目录复制到“测试”。 尝试运行测试并转到$ PROJECT_HOME / target / $ PROJECT_NAME-WEB_INF文件夹中是否包含模板(以防其maven项目无法确定gradle是否使用相同的结构)?

如果它们不存在,则可能必须在pom.xml中定义节点。 看一下文档: http : //maven.apache.org/plugins/maven-resources-plugin/testResources-mojo.html

检查以下示例: https : //github.com/lyncode/jtwig-examples/blob/master/simple-webapp/src/test/java/com/lyncode/jtwig/example/ControllerTest.java

请注意,默认情况下,注释@WebAppConfiguration假定执行目录为项目目录,并且遵循默认的maven结构。

如果在某些IDE上运行测试,则可能不符合此要求。 另外,如果您的项目未遵循默认的Maven结构,则需要在批注中传递webapp目录位置。

查看文档: http : //docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/test/context/web/WebAppConfiguration.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM