javaspring-bootmockitomatcherargument-matcher

How can I mock this argument matchers?


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.


Solution

  • 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));