我如何模拟这个参数匹配器?

How can I mock this argument matchers?

我正在尝试模拟受保护方法的响应,但出现此错误:

Invalid use of argument matchers! 1 matchers expected, 2 recorded:

这是代码:

@Test
public void updateClientSettings() {

    String clientId = "36000150-730a-4808-b04b-2b264862de8a";
    ClientSettings updateSettings = new ClientSettings();
    updateSettings.setHeadline("Any headline");
    updateSettings.setSecondaryLine("Any secondary line");
    byte[] content = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x1, 0x0, 0x1, 0x0, 0x8, 0x0, 0x0, 0x8, 0x8, 0x8, 0x0, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x0, 0x2, 0x2, 0x44, 0x1, 0x0, 0x3b };
    MultipartFile backgroundImage = new MockMultipartFile("image_test.png", "image_test.png", "image/png", content);
    try {
        ClientSettings settings = new ClientSettings();
        settings.setClientId(clientId);
        when(clientSettingsRepository.findByClientId(clientId)).thenReturn(settings);
        boolean validate = true;
        when(clientService.uploadClientBackGroundImage(Mockito.anyString(), any(MultipartFile.class))).thenReturn(validate);
        ServiceResponse response = clientService.updateSettings(clientId, updateSettings, backgroundImage);
        assertNotNull(response);
    } catch (Exception e) {
        fail();
    }
}

我的所有项目只有 1 个 uploadClientBackGroundImage 方法,并接收 2 个参数作为输入

protected boolean uploadClientBackGroundImage(String clientId, MultipartFile backgroundImage) { ...

任何建议将不胜感激。

您必须 spy 来控制正在测试的 class 的行为。除了 @InjectMocks,您还需要添加 @Spy

@Spy
@InjectMocks
private ClientService clientService;

然后像这样控制protected方法的行为。

Mockito.doReturn(validate)
  .when(clientService)
  .uploadClientBackGroundImage(Mockito.anyString(), any(MultipartFile.class));