最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

android - How to test that exception been thrown in Mockk - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论