lundi 2 mars 2015

How to test spring RESTful MVC controller methods?

I've got simple Spring MVC project created in Spring Tool Suite IDE, so project's structure is


enter image description here


I need to test my controller methods, for example



@RequestMapping(value = "/references/{id}", method = RequestMethod.GET)
public @ResponseBody GAReference getReference(@PathVariable("id") int id) {
return server.getReference(id);
}


server is an interface, it has implementation (ServerTestImpl), and there is a ServerTestImpl bean stored in MainControllerContext.xml.


I want my test class to look like in this answer, but I don't have springDispatcher-servlet.xml in my project structure. So, I think it might be like



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/MainControllerContext.xml")
@WebAppConfiguration
public class MainControllerTest {

private MockMvc mockMvc ;

@Autowired
WebApplicationContext wac;

@Autowired
private ServerTestImpl server;

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


@Test
public void testGetReference() {
try {
mockMvc.perform(get("/references/5"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].description", is("Lorem ipsum")))
.andExpect(jsonPath("$[0].title", is("Foo")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].description", is("Lorem ipsum")))
.andExpect(jsonPath("$[1].title", is("Bar")));
} catch (Exception e) {
e.printStackTrace();
}
}

}


How can I test my controller with this project structure? Thanks.


Aucun commentaire:

Enregistrer un commentaire