Android Mockito.verify says Argument(s) are differ

2019-06-01 01:13发布

问题:

The situation

I have an interface of a Tracker which has this method:

fun trackEvent(event: String, args: Bundle? = null)

I want to verify, that this method is called with a specific event. Internally object that being tested call this method with Bundle object. All the events are specified as

companion object {
        const val EVENT = "EVENT"
}

The problem

The test fails with this verification:

Mockito.verify(tracker).trackEvent(Tracker.EVENT)

with message:

Argument(s) are different! Wanted: tracker.trackEvent("EVENT", null); ...

Actual invocation has different arguments: tracker.trackEvent("EVENT", null); ...

There are many solutions, which are using Mockito.eq(), Mockito.refEq(), ArgumentMatchers, Captures, etc. None of them worked for me, giving the same or NullPointerException

回答1:

For those who will face same problem, the solution is that you need to add testImplementation "com.nhaarman:mockito-kotlin:1.5.0" in your build.gradle file. More info, here https://github.com/nhaarman/mockito-kotlin.

The thing is that in Java all classes are nullable by default, unlike Kotlin. While mockito is designed to be used with Java, the library from above adds support using Mockito with Kotlin.

So, the solution to this particular test

Mockito.verify(tracker).trackEvent(Tracker.EVENT)

is

Mockito.verify(tracker).trackEvent(eq(Tracker.ADD_TRANSACTION), any())

where eq() and any() are functions of com.nhaarman.mockito_kotlin.

More info here: https://stackoverflow.com/a/38722935/3569545