4

我有一個控制器,它響應一個調用返回XML數據。下面是代碼Spring MVC控制器的集成測試

@RequestMapping(value = "/balance.xml",method = RequestMethod.GET,produces="application/xml") 
public AccountBalanceList getAccountBalanceList(@RequestParam("accountId") Integer accountId) 
{ 
    AccountBalanceList accountBalanceList = new AccountBalanceList(); 
    List<AccountBalance> list = new ArrayList<AccountBalance>(); 
    list = accountService.getAccountBalanceList(accountId); 

    accountBalanceList.setList(list); 
    return accountBalanceList; 
} 

accountBalanceList標註有xml.The響應我從這個電話得到的是這樣的

<points> 
<point> 
    <balance>$1134.99</balance> 
    <lots>10000.0</lots> 
    <onDate>2012-11-11 15:44:00</onDate> 
</point> 
</points> 

我想寫集成測試此控制器電話。我知道如何用JSON響應來測試控制器,但我不知道如何測試XML的響應時間。任何幫助將不勝感激。

問候

回答

8

假設你在Spring 3.2+你可以使用Spring MVC測試框架(3.2之前它是一個獨立的項目,available on github)。爲了適應從official documentation的例子:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration("test-servlet-context.xml") 
public class AccountIntegrationTests { 

    @Autowired 
    private WebApplicationContext wac; 

    private MockMvc mockMvc; 

    @Before 
    public void setup() { 
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 
    } 

    @Test 
    public void getAccount() throws Exception { 
     Integer accountId = 42; 
     this.mockMvc.perform(get("/balance.xml") 
      .param("accountId", accountId.toString()) 
      .accept("application/json;charset=UTF-8")) 
      .andExpect(status().isOk()) 
      .andExpect(content().contentType("application/xml")); 
      .andExpect(content().xml("<points>(your XML goes here)</points>"));    
    } 
} 

驗證XML文件本身的內容是從響應內容閱讀它的問題。


編輯:回覆:讓XML內容

content()返回ContentResultMatchers一個實例,這對於測試內容本身,這取決於幾種類型的簡便方法。上面的更新示例顯示如何驗證XML響應的內容(請注意:根據文檔此方法需要XMLUnit工作)

+0

謝謝您的回覆。我嘗試了'和Expect(content()。string())',但無法成功獲得結果。我想我還得嘗試其他東西。謝謝 – 2013-04-25 14:49:32

+0

更新了答案,以顯示如何驗證響應是否包含預期的XML 。 – kryger 2013-04-25 15:00:48