我如何嘲笑这个参数匹配器?

时间:2020-05-21 17:59:59

标签: java spring-boot mockito matcher argument-matcher

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

无效使用参数匹配器! 预计有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) { ...

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

@Spy
@InjectMocks
private ClientService clientService;

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

Mockito.doReturn(validate)
  .when(clientService)
  .uploadClientBackGroundImage(Mockito.anyString(), any(MultipartFile.class));
相关问题