Spring MVC Integration Tests
08 Feb 2017Spring Framework provides first class support for MVC Testing. You don’t need to start a servlet to run the test. Starting Spring Framework 3.2 release, Spring MVC Tests are supported. Spring MVC Test Framework simplifies testing of Spring MVC applications using Junit framework.
This can be implemented using Configuration Loader or Standalone Mode
Standalone Mode
Using standalone mode, you can test each controller component independently. This method is preferred if you want to test only certain aspect of controller, hence this method is not usually considered as complete Integration Test. Here’s how you can configure your test to setup standalone component to test in Standalone Mode.
@RunWith(MockitoJUnitRunner.class)
public class QuestionsControllerMVCTest {
private MockMvc mockMvc;
@InjectMocks
private QuestionsController questionsController;
@Mock
private QuestionService mockQuestionService;
@Before
public void setup(){
mockMvc = MockMvcBuilders.standaloneSetup(questionsController).build();
}
@Test
public void testGetQuestions() throws Exception {
List<Question> questionList = Lists.newArrayList(question);
Mockito.when(mockQuestionService.getAllQuestions()).thenReturn(questionList);
mockMvc.perform(get("/questions"))
.andExpect(status().isOk())
//Debugging
.andDo(MockMvcResultHandlers.print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[0].question", Matchers.is("Test Question")))
.andExpect(jsonPath("$.[0].op1", Matchers.is("op1")))
.andExpect(jsonPath("$.[0].op2", Matchers.is("op2")))
.andExpect(jsonPath("$.[0].op3", Matchers.is("op3")))
.andExpect(jsonPath("$.[0].op4", Matchers.is("op4")))
.andExpect(jsonPath("$.[0].answer", Matchers.is("op1")));
}
Configuration Loader
Using this approach, all the configuration/controllers are loaded by the configuration loader and tested using the RestTemplate Requests.
Adding @SpringBootTest
annotation, Spring loads WebApplicationContext required for Test.
@RunWith(SpringRunner.class)
@SpringBootTest
public class GameSessionControllerMVCTest {
String gameSessionJSON;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).dispatchOptions(true).build();
}
@Test
public void testGetAllGameSessions() throws Exception {
mockMvc.perform(get("/sessions"))
.andExpect(status().isOk());
}
@Test
public void testCreateGameSession() throws Exception {
File file = null;
try {
file = ResourceUtils.getFile("src/test/resources/session.json");
gameSessionJSON = new Scanner(file).useDelimiter("\\Z").next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mockMvc.perform(post("/sessions")
.contentType(MediaType.APPLICATION_JSON)
.content(gameSessionJSON))
.andExpect(status().isOk());
}
}