mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.09k stars 198 forks source link

mockedConstruction and context #495

Closed asaha123 closed 7 months ago

asaha123 commented 7 months ago

Hey folks, I have this test where i use mockConstruction to mock Db class constructor:

mockConstruction(Db::class.java).use { mock ->
            val a = App("http://foo.bar:3306")
            `when`(a.db.ping()).thenReturn("PING")
...
}

I now am trying to follow a specific code snippet in Java which will allow me to also assert the constructor arguments:

final List<Object> constructorArgs = new ArrayList<>();
try(MockedConstruction mocks = mockConstruction(SomeClass.class, (mock, context) -> {
    constructorArgs.addAll(context.arguments());
})) {
  new SomeClass("parameter1", "parameter2");
  // iterate through constructorArgs performing assertions
}
...

However, i am new to kotlin and not sure how do I get access to the context for my own code.

Any suggestions? Thanks very much in advance.

asaha123 commented 7 months ago

Wow i did complicate things a lot for me! I just copied and pasted the code in IntelliJ and the automatic code conversion fixed my problem.

Here's my completed test in case it proves useful to someone else:

// DB class

class Db(url: String) {
    init {
        println("connecting to db $url")
    }

    fun ping(): String {
        return "pong"
    }
}

// App class

class App(url: String) {
    val db = Db(url)
}

@Test
    fun `verify constructor arguments`() {
        // tip from https://groups.google.com/g/mockito/c/WqPlcNrvbOw?pli=1
        // https://github.com/mockito/mockito-kotlin/issues/495

        val mockDbUrl = "http://foo.bar:3306"

        // we use this list to store the arguments
        val constructorArgs: MutableList<Any?> = ArrayList()
        mockConstruction(Db::class.java) {
                                         mock, context -> constructorArgs.addAll(context.arguments())
        }.use { mock ->

            App(mockDbUrl)

            assertTrue(mock.constructed().size == 1)

            assertEquals(mockDbUrl, constructorArgs[0])
        }
    }

I will close the issue for now, unless there is a better way to do this - which if there is, please let me know.