0

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

参数匹配器的使用无效!预计 1 个匹配者,记录 2 个:

这是代码:

@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) { ...

任何建议将不胜感激。

4

1 回答 1

0

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

@Spy
@InjectMocks
private ClientService clientService;

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

Mockito.doReturn(validate)
  .when(clientService)
  .uploadClientBackGroundImage(Mockito.anyString(), any(MultipartFile.class));
于 2020-05-21T18:30:44.977 回答