'Junit5 test case for controller layer
@GetMapping(value = "/abc")
public ResponseDto<Map<String, FResponseDto>, Void> getFlightDetails(@RequestParam String fIds) {
Map<String, FResponseDto> response = fService
.getDetails(fIds);
if (Objects.isNull(response)) {
return ResponseDto.failure(FConstants.FLIGHT_NOT_FOUND);
}
return ResponseDto.success(FConstants.SUCCESS,response);
}
how to test this other then status i want to test the if and other return
Solution 1:[1]
This code may help you.
@WebMvcTest(controllers = YourController.class)
class YourControllerTest {
private MockMvc mockMvc;
@Autowired
private YourController controller;
@MockBean
private FService fService;
@BeforeEach
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(controller)
.build();
}
@Test
public void test_getFlightDetails() throws Exception {
Map<String, FResponseDto> data = ......;
Mockito.when(fService.getDetails(anyString())).thenReturn(data);
this.mockMvc.perform(get("/abc"))
.andExpect(status().isOk());
Mockito.when(fService.getDetails(anyString())).thenReturn(null);
this.mockMvc.perform(get("/abc"))
.andExpect(status().is5xxServerError());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | xiaobo9 |
