I've got simple Spring MVC project created in Spring Tool Suite IDE, so project's structure is
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.
By using the org.springframework.web.client.RestTemplate we can test the spring rest/spring-ws applications.
Try the below code snippet on setup
@Before public void setUp($basecontroller controllerobj)
{ this.mockMvc = MockMvcBuilders.standAloneSetup(controllerobj).dispatchOptions(true).build(); }
$basecontroller = base controller of the controllers residing in the same package as the other controllers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.