Spring MVC控制器的集成测试

时间:2013-04-25 07:27:09

标签: spring-mvc model-view-controller integration-testing spring-mvc-test

我有一个控制器,它响应一个调用返回XML数据。以下是代码

@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注释。我从此调用中获得的响应就像这样

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

我想为此控制器调用编写集成测试。我知道如何使用JSON响应测试控制器,但我不知道如何测试响应是否在XML中。任何帮助将不胜感激。

此致

1 个答案:

答案 0 :(得分: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工作的文档)

相关问题