-
Notifications
You must be signed in to change notification settings - Fork 0
MockK: Testing private methods using spyK
Devrath edited this page Mar 2, 2024
·
1 revision
- MockK is a framework that is used to
create mocks
,stub behaviors
, andverify interactions with your tests
. - And when it comes to testing private methods we can use
spyK
.
class PrivateClassUnderDemoTest {
@Test
fun testPrivateMethod() {
// <--------------------> Arrange <-------------------->
val resultToCheck = "Mocked Private result!"
val privateMethodName = "privateMethod"
// <--------------------> Act <------------------------>
// Create a spy of our class
val ourClass = spyk( PrivateClassUnderDemo() )
// Stub a private method to return a value
every { ourClass[privateMethodName]() } returns resultToCheck
// Call the public method, That will invoke the public method
val result = ourClass.publicMethod()
// <--------------------> Assert <-------------------->
// Assert the result
assertEquals(resultToCheck, result)
}
}
class PrivateClassUnderDemo {
private fun privateMethod(): String {
return "Hello, Private!"
}
fun publicMethod(): String {
return privateMethod()
}
}