0

I'm trying to mock a reponse from a protected method and I'm getting this error:

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

This is the code:

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

I only have 1 uploadClientBackGroundImage method on all my project, and receives 2 parameters as input

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

Any advices will be really appreciated.

  • is ur clientService a mock object or spy or stub ? – Amit Kumar Lal May 21 '20 at 18:11
  • is a InjectedMock – Francisco Noguera May 21 '20 at 18:17
  • Just a note - the `try` and `catch` in your test are unnecessary and will make things harder for you. If a test throws an exception without catching it, the exception will get reported by the test framework and the test will fail. This is what you want to happen. With the code that you've written, the details of the exception will get thrown away, which makes it more difficult to fix. – Dawood ibn Kareem May 21 '20 at 18:40

1 Answers1

0

You have to spy to control behaviour of class which is under test. Along with @InjectMocks, you need to add @Spy also.

@Spy
@InjectMocks
private ClientService clientService;

And then control the behaviour of protected method like this.

Mockito.doReturn(validate)
  .when(clientService)
  .uploadClientBackGroundImage(Mockito.anyString(), any(MultipartFile.class));
lucid
  • 2,722
  • 1
  • 12
  • 24