Spring MVC gives a test framework which MockMvc provides simulation of a servlet container. Its like your running on a mock server. This will help to test all your REST controllers from junit
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:dispatch-servlet.xml" })
public class XXXXXXXXXControllerTest {
@Autowired
XXXXXXController xxxxxxxxxController;
...
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(xxxxxxxxxController).build();
...
@Test
public void shouldXXXXXXXXXXXXXXXXXXXXXX() {
mockMvc.perform(get("/a/1").accept(MediaType.APPLICATION_JSON)).
andExpect(status().isOk())
.andExpect(content().string("yyyyyyyyyyyyyyyyyyy"));
}
}
Above is only if we know the name of the controller class. This is good for unit testing the controller classes
OR if you not need to use a given spring config you can use WebApplicationContext as below
@WebAppConfiguration
public class YYYYYYYYYY{
MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
protected void shouldXXXXXXXXX() {
getMockMvc().perform(get(restCall)).andExpect(status().isOk());
}
}
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:dispatch-servlet.xml" })
public class XXXXXXXXXControllerTest {
@Autowired
XXXXXXController xxxxxxxxxController;
...
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(xxxxxxxxxController).build();
...
@Test
public void shouldXXXXXXXXXXXXXXXXXXXXXX() {
mockMvc.perform(get("/a/1").accept(MediaType.APPLICATION_JSON)).
andExpect(status().isOk())
.andExpect(content().string("yyyyyyyyyyyyyyyyyyy"));
}
}
Above is only if we know the name of the controller class. This is good for unit testing the controller classes
OR if you not need to use a given spring config you can use WebApplicationContext as below
@WebAppConfiguration
public class YYYYYYYYYY{
MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
protected void shouldXXXXXXXXX() {
getMockMvc().perform(get(restCall)).andExpect(status().isOk());
}
}
Thanks, this is eally helpful
ReplyDelete