Mockito 'Misplaced argument detected here' in Java

20,571

The culprit is this part:

.thenReturn(any(Orientation.class))

any() is supposed to be used in conjunction with When.

Do something like this:

@Mock
private Orientation orientationMock;

// ...

.thenReturn(orientationMock);
Share:
20,571

Related videos on Youtube

stack man
Author by

stack man

hello world

Updated on October 03, 2020

Comments

  • stack man
    stack man over 3 years

    So I have this Mockito unit test:

    @Test
        public void createCard() {
    
        when(jwtServiceMock.getId(anyString())).thenReturn(validUserToken);
        when(profileServiceMock.getProfile(validUserToken)).thenReturn(mock(Profile.class));
        when(cardServiceMock.countViewableCardsCreatedOrOwnedBy(anyObject())).thenReturn(5L);
        when(cardServiceMock.countCardsCreatedOrOwned(anyObject())).thenReturn(10L);
    
        final Card expectedCard = getCard();
    
        when(cardServiceMock.createCard(anyString(), anyListOf(String.class), anyListOf(String.class),
                any(CreatorRecipientCriteria.class), anyListOf(ImageMask.class))).thenReturn(expectedCard);
    
        when(imageService.createCardImage(any(MultipartFile.class), anyString(), any(ImageMask.class))).thenReturn(any(Orientation.class));
    
        final Card receivedCard = cardControllerMock.createCard(validUserToken, mock(MultipartFile.class), "card");
    
        assertEquals(receivedCard, expectedCard);
    }
    

    It looks fine for me, but for some reason it says:

    org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
    Misplaced argument matcher detected here:
    
    -> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:53)
    
    You cannot use argument matchers outside of verification or stubbing.
    Examples of correct usage of argument matchers:
        when(mock.get(anyInt())).thenReturn(null);
        doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
        verify(mock).someMethod(contains("foo"))
    

    I have been trying to find out what's wrong for a long time, but still not sure what's causing the issue. Any hint please?

    Thanks.

    • Tunaki
      Tunaki over 8 years
      Try to replace when(imageService.createCardImage(any(MultipartFile.class), anyString(), any(ImageMask.class))).thenReturn(any(Orientation.class)); with when(imageService.createCardImage(any(MultipartFile.class), anyString(), any(ImageMask.class))).thenReturn(mock(Orientation.class));