mockito-kotlin
mockito-kotlin copied to clipboard
Verifying multiple calls with check function logs assertion error
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
- mockito-kotlin version: 2.2.0
- OS: OSX
- Kotlin version: 1.3.60
- JDK version: 11
- JUnit version: 5.5.2
- AssertJ version: 3.13.2
- Type of test: unit test
@larmic You should take a look at this.
@bohsen Hmm, but I want to do more assertions on the received argument. id and text of Tweet.kt.
Use eq() or argThat(). I believe it's mentioned in the issue I referred to.
Maybe you can refactor my code above? argThat only verifies one attribute at all.
I could, but I'm not going to.
Ok :/ I did not see the trick.
@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))