简体   繁体   中英

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

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());
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM