Reputation: 1479
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.
Upvotes: 3
Views: 5994
Reputation: 3105
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)
}
}
Upvotes: 6