Skip to content

Instantly share code, notes, and snippets.

@gohilronak
Created December 14, 2018 12:51
Show Gist options
  • Save gohilronak/029bf97181201891d1de9feffa2d4300 to your computer and use it in GitHub Desktop.
Save gohilronak/029bf97181201891d1de9feffa2d4300 to your computer and use it in GitHub Desktop.
Unit Test REST endpoint with MockMvc and check if status is 200 OK
package com.example.tdd.controller;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
/**
* @WebMvcTest annotation will load only a small part of spring web application
* context instead of full spring application context as
* in @SpringBootTest
* @author Ronak
*
*/
@RunWith(SpringRunner.class)
@WebMvcTest(CarController.class)
public class CarControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void getCar_shouldReturnCar() throws Exception {
// Make request to controller through spring only.
// This does not involve tomcat or any network call.
ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/cars/prius"))
.andExpect(status().isOk());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment