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