I have written unit test cases for a spring rest controller but I'm getting blank response body.
Below is my controller class
@RestController
@RequestMapping("/v2")
public class controller {
@Autowired
Service service;
@RequestMapping(value="/health",method=RequestMethod.POST)
public String postRequest(@RequestHeader @NotNull@NotBlank String
transID) {
return service.getTest(transID); }
}
Below is my service class
@Component
public class Service {
public String getTest(@NotNull String transid) {
return "Hello World Test";
} }
Below is my Unit Test class.I have written the unit test case for this method using mockito
class UnitTest {
@InjectMocks
controller controllerUse;
@Mock
Service service;
@Autowired
MockMvc mockMvc;
@BeforeEach
public void test() {
MockitoAnnotations.initMocks(this);
mockMvc=MockMvcBuilders.standaloneSetup(controllerUse).build();
}
@Test
public void confirmTest() throws Exception {
mockMvc.perform(post("/v2/health")
.header("transID","ABC"))
.andExpect(status().isOk())
.andDo(print())
.andReturn(); }
}
The OutPut:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
I am getting response code as 200. but getting blank body.what am i missing? is this the standard way of writing unit test cases for spring rest controller?
Since you are injecting mock bean service, you need to mock method with your expected response.
Here is sample code using Junit 5 and Spring Boot Test artifact but you can achieve same using standard spring test module as well.
@WebMvcTest(SampleController.class)
class SampleControllerTest {
@MockBean
Service service;
@Autowired
private MockMvc mockMvc;
@Test
public void confirmTest() throws Exception {
when(service.getTest("ABC")).thenReturn("Hello World");
mockMvc.perform(post("/v2/health")
.header("transID", "ABC"))
.andExpect(status().isOk())
.andDo(print())
.andReturn();
}
}
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.