如何在 Spring RestController 中测试带有 body 的 GET 请求?

How to test GET request with body in Spring RestController?

我有一个这样的休息控制器;

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

}

我想为它编写一个单元测试,但我无法模拟 service 到 return 列表。

这是我的poFilterCriteria模型;

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

这是我的测试;

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

}

但是应该 return 大小为 1 的列表 return 是空的。 我做错了什么?

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

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

org.mockito.ArgumentMatchers#相同

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