Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integration Tests of Spring MVC controller

I have a controller which returns XML data in response of a call. Below is the code

@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 is annotated with xml.The response I am getting from this call is like this

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

I want to write integration test for this controller call. I know how to test a controller with JSON response but I don't know how to test when the response is in XML.Any help will be appreciated.

Regards

like image 471
Bilal Nasir Avatar asked Apr 25 '13 07:04

Bilal Nasir


1 Answers

Assuming you're on Spring 3.2+ you could use the Spring MVC Test Framework (before 3.2 it was a standalone project, available on github). To adapt the example from the 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>"));               
    }
}

Verifying the contents of the XML file itself would be a matter of reading it from the response content.


EDIT: Re: getting XML contents

content() returns an instance of ContentResultMatchers, which has several convenience methods for testing the content itself, depending on type. Updated example above to show how to verify contents of XML response (please note: according to the documentation this method needs XMLUnit to work)

like image 96
kryger Avatar answered Sep 19 '22 23:09

kryger