2

I try to write integration tests for my spring MVC app.

Problem:

It seems that TilesView can't resolve views in my spring mvc tests. In my test MockMvcResultMatchers.forwardedUrl() returns "/WEB-INF/jsp/layout.jsp", instead of "/WEB-INF/jsp/manageEntities.jsp"

*My app works fine, problems exist only in tests!

See '//Assertion error' comment in my test class

Code:

Maybe code will be more explanatory than words. I tried to make it as clear as it possible.

Controller:

@Controller
public class MyController {

@RequestMapping("/manageEntities.html")
public String showManageEntitiesPage(Map<String, Object> model) {
    //some logic ...
    return "manageEntities";
}

Test:

@WebAppConfiguration
@ContextHierarchy({
        @ContextConfiguration(locations = { "classpath:ctx/persistenceContextTest.xml" }),
        @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/servlet.xml" })
})
@RunWith(SpringJUnit4ClassRunner.class)
public class EntityControllerTest {

    @Autowired
    protected WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        this.mockMvc = webAppContextSetup(this.wac).build();
    }

     @Test // FAILS!!
    public void entity_test() throws Exception {

        //neede mocks 
        //........

        mockMvc.perform(get("/manageEntities.html"))
                .andExpect(status().isOk())
                .andExpect(forwardedUrl("/WEB-INF/jsp/manageEntities.jsp")); //Assertion error!!!
    }
}

tiles.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
    <definition name="base.definition" template="/WEB-INF/jsp/layout.jsp">
    <put-attribute name="title" value="" />
    <put-attribute name="header" value="/WEB-INF/jsp/header.jsp"/>
    <put-attribute name="menu" value="/WEB-INF/jsp/menu.jsp" />
    <put-attribute name="body" value="" />
    <put-attribute name="footer" value="/WEB-INF/jsp/footer.jsp" />
    </definition>

    <definition name="manageEntities" extends="base.definition">
        <put-attribute name="title" value="Manage Entities"/>
        <put-attribute name="body" value="/WEB-INF/jsp/manageEntities.jsp"/>
    </definition>
//....

AssertionError:

java.lang.AssertionError: Forwarded URL expected:</WEB-INF/jsp/manageEntities.jsp> but was:</WEB-INF/jsp/layout.jsp>
4

1 回答 1

4

你的断言是错误的。您正在使用Tiles并且因此ViewResolver也被咨询,请记住您基本上是在进行集成测试而不是单元测试。您正在测试一起工作的整个组件链。

您需要ViewResovler为您的测试切换,基本上使您的测试不那么有价值,因为您没有测试实际配置,或者找到另一个验证响应。(例如,您可能需要内容并检查标题)。

mockMvc.perform(get("/manageEntities.html"))
            .andExpect(status().isOk())
            .andExpect(content().source(containsString("Manage Entities"));

基本上上面检查结果页面,以包含给定的字符串。(从我的头顶开始,可能需要一些调整)。

更多信息

  1. MockMvcResultMatchers
  2. 内容结果匹配器
于 2013-09-16T13:30:41.307 回答