r-hold
r-hold

Reputation: 1120

Mockito / Powermock: matcher any() falsely does not match (but anyOrNull() does

I am using Mockito / Powermock in an Android unit test, written in Kotlin. I have code as follow:

verify(myCompanionMock, atLeastOnce()).someMethod(any(), any())

But I get this error:

Comparison Failure: 
<Click to see difference>

Argument(s) are different! Wanted:
companion.someMethod(
    <any java.io.File>,
    <any java.io.File>
);
-> at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:182)
Actual invocation has different arguments:
companion.someMethod(
    null,
    null
);

accordingly if I replace the matcher any() with anyOrNull() the test runs through. I have stepped in with a debugger to verify, that actual File objects (which are not mocks) are passed to someMethod(). I also verified that the mocking of the static Companion objects works. (All other tests on it run as expected).

The static Companion class is written in Kotlin. The Class under Test calling the Companion is written in Java. The @PrepareForTest-annotations for those classes are correctly set (all other tests working as expected)

So I am wondering if I missed something or this is a problem with the Mockito matchers I am not aware of?

Upvotes: 1

Views: 1408

Answers (1)

GreenhouseVeg
GreenhouseVeg

Reputation: 647

This seems to be the recommended way of using argument matchers with PowerMock:

// class containing static method
public class Companion {
    public static void someMethod(File a, File b) { }
}

// test class
@RunWith(PowerMockRunner.class)
@PrepareForTest(Companion.class)
public class CompanionTest {

    @Test
    public void testCompanion() {

        PowerMockito.mockStatic(Companion.class);

        // call method with non-null arguments
        Companion.someMethod(Mockito.mock(File.class), Mockito.mock(File.class));

        // verify
        PowerMockito.verifyStatic(Companion.class);
        Companion.someMethod((File) ArgumentMatchers.notNull(), 
                             (File) ArgumentMatchers.notNull());
    }
}

This worked for me using JUnit 4, Mockito 2.28.2 and PowerMock 2.0.2.

Upvotes: 0

Related Questions