Home > Software engineering >  How to test GET request with body in Spring RestController?
How to test GET request with body in Spring RestController?

Time:04-05

I have a rest controller like this;

@RestController
@RequiredArgsConstructor
@RequestMapping(PO)
public class PoController {

    private final PoService service;

    @GetMapping(value = FILTER, produces = APPLICATION_JSON_VALUE)
    public ResponseEntity<List<PoDTO>> filter(PoFilterCriteria poFilterCriteria) {
        return ok().body(service.getPos(poFilterCriteria));
    }

}

And I want to write an unit test for it but I couldn't achieve to mock the service to return list.

This is my poFilterCriteria model;

@Data
public class PoFilterCriteria {
    private double hp;
    private FilterOperationType hpOperationType;
    private double attack;
    private FilterOperationType attackOperationType;
    private double defense;
    private FilterOperationType defenseOperationType;
}

And this is my test;

@WebMvcTest(value = PoController.class)
class PoControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private PoService service;

    private PoDTO poDTO;

    private List<PoDTO> poDTOList;

    @BeforeEach
    void setUp() {
        poDTOList = new ArrayList<>();
        poDTO = new Po();
        poDTOList.add(poDTO);
    }

    @Test
    public void filter_success() throws Exception {
        PoFilterCriteria poFilterCriteria= new PoFilterCriteria ();
        poFilterCriteria.setAttack(40);
        poFilterCriteria.setAttackOperationType(GT);
        poFilterCriteria.setHp(49);
        poFilterCriteria.setHpOperationType(EQ);
        poFilterCriteria.setDefense(60);
        poFilterCriteria.setDefenseOperationType(LT);
        when(service.getPos(poFilterCriteria)).thenReturn(poDTOList);

        mockMvc.perform(get(PO   FILTER)
                        .param("hp", String.valueOf(40))
                        .param("hpOperationType", String.valueOf(GT))
                        .param("attack", String.valueOf(49))
                        .param("attackOperationType", String.valueOf(EQ))
                        .param("defense", String.valueOf(60))
                        .param("defenseOperationType", String.valueOf(LT))
                        .contentType(APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().json(new ObjectMapper().writeValueAsString(poDTOList)));
    }

}

But the list that should return with size of 1 is returning empty. What did I do wrong?

CodePudding user response:

org.mockito.ArgumentMatchers#any(java.lang.Class)

when(service.getPos(any(PoFilterCriteria.class))).thenReturn(poDTOList);

or

org.mockito.ArgumentMatchers#same

when(service.getPos(same(poFilterCriteria))).thenReturn(poDTOList);
  • Related