mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.11k stars 202 forks source link

Verifying multiple calls with check function logs assertion error #367

Open larmic opened 4 years ago

larmic commented 4 years ago

Hi,

I'dont now if this is a bug. I'm trying to verify two arguments by using check {}. Of course I can use an argument capture, but I'm expecting this should working too.

import com.nhaarman.mockitokotlin2.check
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.internal.verification.Times

class Tweet(val id: Int, val text: String)

interface TweetRepository {
    fun persist(tweet: Tweet)
}

class TweetTest {

    @Test
    internal fun `verify multiple perists`() {
        val repositoryMock = mock<TweetRepository>()

        repositoryMock.persist(Tweet(1, "first tweet"))
        repositoryMock.persist(Tweet(2, "second tweet"))

        verify(repositoryMock, Times(1)).persist(check {
            assertThat(it.id).isEqualTo(1)
            assertThat(it.text).isEqualTo("first tweet")
        })
        verify(repositoryMock, Times(1)).persist(check {
            assertThat(it.id).isEqualTo(2)
            assertThat(it.text).isEqualTo("second tweet")
        })
    }
}

is green but logs assertion errors

org.opentest4j.AssertionFailedError: 
Expecting:
 <2>
to be equal to:
 <1>
but was not.
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

Context

bohsen commented 4 years ago

@larmic You should take a look at this.

larmic commented 4 years ago

@bohsen Hmm, but I want to do more assertions on the received argument. id and text of Tweet.kt.

bohsen commented 4 years ago

Use eq() or argThat(). I believe it's mentioned in the issue I referred to.

larmic commented 4 years ago

Maybe you can refactor my code above? argThat only verifies one attribute at all.

bohsen commented 4 years ago

I could, but I'm not going to.

larmic commented 4 years ago

Ok :/ I did not see the trick.

bohsen commented 4 years ago

@larmic Or create your own TweetMatcher.

But eq() is the easiest.

val tweet1 = Tweet(1, "first tweet")
val tweet2 = Tweet(2, "second tweet")
verify(repositoryMock, Times(1)).persist(eq(tweet1))
verify(repositoryMock, Times(1)).persist(eq(tweet2))