简体   繁体   中英

MockK Kotlin: Verification failed: call 1 of 1: was not called

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"

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()
}

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