Skip to content

Argument matcher check called twice when the mocked method was only called once. #532

Open
@roy-t

Description

@roy-t

When I was writing a test that required a more complex argument matcher I resorted to using check. To my surprise check is evaluated twice when the mocked method was only called once. I believe this is a bug as I think it is reasonable to assume that if a method is called once the argument matchers for each argument of that method are also only called once. Otherwise you might run into problems (as I did) if the arguments can change state.

I managed to get the reproduction down to this, but I did not get much wiser from the stack trace or mockito-kotlin source code to get any further insights.

import org.junit.jupiter.api.Test
import org.mockito.kotlin.check
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import java.util.concurrent.atomic.AtomicInteger
 
class Tests {       
    @Test
    fun testCase() {
        // Create something that we can mock, note counter is not touched
        class Foo {
            fun bar(counter: AtomicInteger) {}
        }

        // Create the mock, again the counter is not touched
        val mocked =
            mock<Foo> {
            }

        val counter = AtomicInteger(0)

        // Call bar exactly once, verify that the counter is still untouched
        mocked.bar(counter)
        assertThat(counter.get()).isEqualTo(0)

        // Verify that bar was indeed called exactly once  
        verify(mocked, times(1))
            .bar(
                // Check how many times the argument matcher runs, by increment the counter each time
                check { it.incrementAndGet() },
            )

        // We would expect counter to now be 1, but it is actually 2, so this assert fails.
        assertThat(counter.get()).isEqualTo(1)
    }
 }

I'm using the following dependencies:

  • mockito-kotlin 5.4.0
  • junit 5.10.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions