Mockito 'Misplaced argument detected here' in Java

萝らか妹 提交于 2020-12-25 01:32:34

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/32909129/mockito-misplaced-argument-detected-here-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!