I'm trying to essentially test whether a specific method in my class calls a different method properly. I'll remove all unneeded code, so basically my code is as follows:
public class Monitor {
protected void onMessage(String message) {
Log.d(TAG, "Detected the message")
changeOptions();
}
protected void changeOptions() {
Log.d("Reached changeOptions() method");
}
}
RunWith(RobolectricTestRunner::class)
class MonitorTest {
private lateinit var mymonitor : Monitor
@MockK private lateinit var mockContext : Context
@Before
fun setup() {
init(this, relaxed = true)
mockkConstructor(Monitor::class)
every { anyConstructed<Monitor>().getApplicationContext() } returns mockContext
mymonitor = Monitor()
mymonitor.init()
}
@Test
fun test_onMessage() {
val testString : String = "hello"
mymonitor.onMessage(testString)
verify(exactly = 1) {mymonitor.changeOptions());
}
}
However, with this code I get the following error:
java.lang.AssertionError: Verification failed: call 1 of 1: Monitor(mockkConstructor<Monitor>()).changeOptions() was not called.
Calls to same mock:
1) Monitor(mockkConstructor<Monitor>()).getApplicationContext()
2) Monitor(mockkConstructor<Monitor>()).onMessage("hello")
Is there any advice on this?
Note: I KNOW the changeOptions() method is being called because in my terminal output, it prints:
TAG "Detected the message"
TAG "Reached changeOptions() method"
CodePudding user response:
In order to be able to verify the execution, the class must be a mock or a spy, in your case spy applies since you need the real code to be executed, it would look like this:
@Before
fun setup() {
init(this, relaxed = true)
mockkConstructor(Monitor::class)
every { anyConstructed<Monitor>().getApplicationContext() } returns mockContext
mymonitor = spyK(Monitor())
mymonitor.init()
}