admin管理员组

文章数量:1391937

I need to verify that exception been thrown or that some logging method been called. Here is my code

fun stop() {
    println("----")
    CoroutineScope(Dispatchers.IO).launch {
        try {
            internalMqttClient.disconnectForcibly()
               } catch (e: Exception) {
            internalLogger.logError(DEFAULT_LOG_TAG, "1111")

Here is my test

@Test
fun test2()= runTest{
    every { internalMqttClient.disconnectForcibly() } throws Exception()

    subject.stop()
    advanceUntilIdle()
    verify(exactly = 1) {
        internalLogger.logError(
            DEFAULT_LOG_TAG,
            "1111") }
    }
}

And here is the error

java.lang.AssertionError: Verification failed: call 1 of 1: InternalLogger(#3).logError(eq(mqttLibrary), eq(1111))) was not called

I need to verify that exception been thrown or that some logging method been called. Here is my code

fun stop() {
    println("----")
    CoroutineScope(Dispatchers.IO).launch {
        try {
            internalMqttClient.disconnectForcibly()
               } catch (e: Exception) {
            internalLogger.logError(DEFAULT_LOG_TAG, "1111")

Here is my test

@Test
fun test2()= runTest{
    every { internalMqttClient.disconnectForcibly() } throws Exception()

    subject.stop()
    advanceUntilIdle()
    verify(exactly = 1) {
        internalLogger.logError(
            DEFAULT_LOG_TAG,
            "1111") }
    }
}

And here is the error

java.lang.AssertionError: Verification failed: call 1 of 1: InternalLogger(#3).logError(eq(mqttLibrary), eq(1111))) was not called
Share Improve this question asked Mar 12 at 16:04 Bob RedityBob Redity 6311 gold badge8 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Try to parameterize the Dispatcher to be configurable according to the context. If the code uses Dispatchers.Main or Dispatchers.IO, it would be advisable to allow injecting it as a parameter. In this way, a TestDispatcher can be provided in the tests, ensuring that the execution occurs at the right time.

本文标签: androidHow to test that exception been thrown in MockkStack Overflow