Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

android - Mockito Kotlin rejects to work with extensions

In my unit tests, I have a pretty simple case - mocked class with a method call mocking. Something like this:

@Mock
private lateinit var feedbackManager: FeedbackManager
...
Mockito.`when`(feedbackManager.sendFeedbackToEmail(any())).thenReturn(Completable.complete())

So this works perfectly, and I can mock and verify the method call. No problem.

I decided to improve this a bit and added an extension to my FeedbackManager which looks like this:

fun FeedbackManager.mockSendFeedbackToEmail(feedbackText: String = any()) {
    Mockito.`when`(this.sendFeedbackToEmail(feedbackText)).thenReturn(Completable.complete())
}

As you can see everything is the same inside this extension as it was before adding it. But for some reason this approach doesn't work:

java.lang.NullPointerException: Parameter specified as non-null is null: method
package.FeedbackManagerMockingKt.mockSendFeedbackToEmail, parameter feedbackText

Can you please advise here? Is it possible to achieve what I want?

question from:https://stackoverflow.com/questions/65883226/mockito-kotlin-rejects-to-work-with-extensions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that ArgumentMatchers.any() returns null, which does not play well with Kotlin non-nullable types. If it works in your first snippet, then the sendFeedbackToEmail argument must be nullable I guess (or it's a Java class). But the feedbackText in the mockSendFeedbackToEmail is not nullable, so Kotlin compiler inserts null-checks there. Thus the NullPointerException.

Try changing the method signature to:

fun FeedbackManager.mockSendFeedbackToEmail(feedbackText: String? = any()) {
  ...
}

If the sendFeedbackToEmail argument is not nullable and you are using com.nhaarman.mockito_kotlin, you can try the following:

fun FeedbackManager.mockSendFeedbackToEmail(feedbackText: String? = null) {
    Mockito.`when`(this.sendFeedbackToEmail(feedbackText ?: any())).thenReturn("OK")
}

or just overload the function instead of using default value (to avoid a bit misleading calls like: feedbackManager.mockSendFeedbackToEmail(null)):

fun FeedbackManager.mockSendFeedbackToEmail() {
    Mockito.`when`(this.sendFeedbackToEmail(any())).thenReturn("OK")
}

fun FeedbackManager.mockSendFeedbackToEmail(feedbackText: String) {
    Mockito.`when`(this.sendFeedbackToEmail(feedbackText)).thenReturn("OK")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...