2013-09-16 130 views
2

我嘗試爲我的Spring MVC應用程序編寫集成測試。Spring MVC + Tiles:集成測試

問題:

似乎TilesView的解決不了我的Spring MVC的測試意見。 在我的測試MockMvcResultMatchers.forwardedUrl()返回「/WEB-INF/jsp/layout.jsp」,而不是「/WEB-INF/jsp/manageEntities.jsp」

*我的應用程序工作正常,只是存在的問題在測試中!在我的測試類

參見 '//斷言錯誤' 評論

代碼:

也許代碼會多字的說明。我試圖儘可能地把它弄清楚。

控制器:

@Controller 
public class MyController { 

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

測試:

@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> 
//.... 

Asse田:

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

回答

4

你的說法是錯誤的。您正在使用,因此ViewResolver也被諮詢過,請記住,您基本上正在進行集成測試而非單元測試。您正在測試整個組件鏈一起工作。

您需要爲您的測試切換ViewResovler,基本上使您的測試不那麼有價值,因爲您沒有測試實際配置,或找到另一個驗證響應。 (您可能需要內容並檢查標題)。

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

基本上上述檢查結果頁面,包含給定的字符串。 (從我的頭頂可能需要一些調整)。

更多信息

  1. MockMvcResultMatchers
  2. ContentResultMatchers
+0

請,更多的細節。你的意思是找到另一個驗證答覆。 –

+0

修改我的答案。 –