我如何 mock 这个参数匹配器?

2020年10月16日 28点热度 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) { ...

任何建议将不胜感激。

解决方案如下:

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

@Spy
@InjectMocks
private ClientService clientService;

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

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