简体   繁体   中英

Java Mockito Invalid use of argument matchers

I have the following code

public MessageProcessorTest() {
    _logger = mock(Logger.class);
    _context = mock(ExecutionContext.class);

    when(_context.getLogger()).thenReturn(_logger);
    doNothing().when(_logger).log(any(), anyString());

    _mapper = mock(IMapper.class);

    _processor = new MessageProcessor(_mapper, _context);
}

@Test
public void testOutputSourceIsMapped() throws SentenceException
{
    String inputString = "some string";
    when(_mapper.Map(any())).thenReturn(any());

    _inputMessage = new ProcessMessage(inputString, new Date().toString());

    ProcessResult result = _processor.Process(_inputMessage);

    assertNotNull(result);
    assertNotNull(result.GetOriginalMessage());
    assertNotNull(result.OutputMessage);
    assertTrue(result.IsSuccessful);

    Raw rawResult = new Gson().fromJson(result.OutputMessage, Raw.class);

    assertEquals(FeedSources.S.toString(), rawResult.GetSource());
}

And I get the following error

detailMessage:"\nInvalid use of argument matchers!\n0 matchers expected, 1 recorded:\n-> at com.emsa.hpims.processor.MessageProcessorTest.testOutputSourceIsMappedToSatAis(MessageProcessorTest.java:61)\n\nThis exception may occur if matchers are combined with raw values:\n    //incorrect:\n    someMethod(anyObject(), "raw String");\nWhen using matchers, all arguments have to be provided by matchers.\nFor example:\n    //correct:\n    someMethod(anyObject(), eq("String by matcher"));\n\nFor more info see javadoc for Matchers class.\n"

When executing the following line

_context.getLogger().log(Level.FINE, "Some log message");

I've read a bit about it but i'm not understanding what exactly am I doing wrong. Is anyone able to help me?

Thank you.

The problem is most likely this line:

when(_mapper.Map(any())).thenReturn(any());

Here, you tell Mockito to return any() (which returns a matcher) when mapper.map() is invoked with anything.

The whole point with mocking is to allow the user to specify exactly what is returned by mocked methods. You have basically told Mockito to return anything when the method is called, which is not allowed.

What should the method return for you to allow to implement the test case? Replace the second any() with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM