为什么我在这里得到 InvalidUseOfMatchersException?

Why am I getting InvalidUseOfMatchersException here?

我的测试用例出现以下错误:

junit.framework.AssertionFailedError: Exception occured :
        org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
        Invalid use of argument matchers!
        2 matchers expected, 1 recorded:

这是我的一段代码:

Mockito.when(mockHelloPeristenceImpl.retrieveHellorequest(Mockito.anyLong()))
              .thenReturn(Mockito.any(Hellorequest.class));

我尝试了互联网上针对此问题建议的所有选项,但均无济于事。 怎么了?

你不能 return 一个 Matcher 你正在做的事情。您必须指定 您正在 return 的实际对象。要么做这样的事情:

Mockito.when(mockHelloPeristenceImpl.retrieveHellorequest(Mockito.anyLong()))
       .thenReturn(Mockito.mock(Hellorequest.class));

或者,给它一个回答策略,例如

Mockito.when(mockHelloPeristenceImpl.retrieveHellorequest(Mockito.anyLong()))
       .then(Mockito.RETURNS_MOCKS);

顺便说一句,您的代码可以使用以下方法缩短很多:

import static org.mockito.Mockito.*;

那么您的测试语句将是:

when(mockHelloPeristenceImpl.retrieveHellorequest(anyLong()))
          .then(RETURNS_MOCKS);