Search code examples
javajunitmockingmockito

Mockito Matcher parameters showing as undefined


I am trying to Mock a method contained in the Main class of an application. I'd like to test that when all parameters are submitted successfully, the application calls the correct method, uploadFiles. The when - thenReturn pair is shown below:

NrClient nrClient = (NrClient)Mockito.mock(NrClient.class);
Mockito.when(nrClient.uploadFiles("DF49ACBC8", anyList(), "dl")).thenReturn("");

This shows as a runtime exception: "The method anyString() is undefined for the type MainTest." I have the imports:

import org.mockito.Mockito;
import org.mockito.Matchers;

So why would this method be undefined? Is there an issue in my implementation?

I have also tried anyString() and anyInt() with the same result.


Solution

  • You should be getting it as a compile-time error, not an exception (unless the actual exception is that you've got an unresolved compile-time error).

    Just importing org.mockito.Matchers means you can use the name Matchers to mean org.mockito.Matchers anywhere in the class. If you want to import the methods, you need a static wildcard import:

    import static org.mockito.Matchers.*;
    

    Or specific methods:

    import static org.mockito.Matchers.anyString;
    import static org.mockito.Matchers.anyList;
    

    Or you could just qualify the method name in the calling code instead:

    Mockito.when(nrClient.uploadFiles("DF49ACBC8", Matchers.anyList(), "dl"))
           .thenReturn("");