简体   繁体   中英

MockK's spyk how to overwrite constructor?

I currently try to test a class as a spy object that normally initialize a database connection in the constructor. The a simplified version of the class looks like this.

class classToTest(){
    val connection:Connection

    init {
        connection = DatabaseConnection(url="127.0.0.1")
    }

    fun methodA():Int{
       return 3
    }
}

Now i try to test the methods of my classToTest in the following way (simplified).

class TestClass(){
    var connection = mockk<DatabaseConnection>()
    var dbh = spyk(ClassToTest())

    @Test
    fun testMethodA(){
       assertEquals(dbh.methodA,3)
    }
}

The problem is now that my test can not start because i don't know how to overwrite the init function that may connection mock is used instead of initialize a connection object. Thanks for help.

I don't think there is a way to mock the init function of a spy.

I suggest you to use the constructor to pass an instance of the connection.

class ClassToTest(val connection: Connection) {
    ...
}

Then in your test it's super easy to mock the connection.

class TestClass(){
    private val dbh = ClassToTest(mockk())

    @Test
    fun testMethodA() {
       assertEquals(dbh.methodA, 3)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM