下面涉及异常的代码如何编写MockK单元测试

How to write a MockK unit test for the following code involving exceptions

我刚开始使用 Kotlin 编写代码,之前从未使用过 MockK。我想知道如何为 schedule() 函数编写 mockk 测试并测试 RejectedExecutionException。

  fun schedule() {
            try {
                executor.scheduleAtFixedRate(this, 0, 1, TimeUnit.HOURS)
            } catch (e: RejectedExecutionException) {
                logger.warn("Encountered an exception: $e")
            }
        }

您可以使用 assertThrows 测试异常:

// executor must be defined as mockk 
every { executor.scheduleAtFixedRate(any(), any(), any(), any()) } throws RejectedExecutionException("Exception Message")
val ex = assertThrows<RejectedExecutionException> {
            obj.schedule()
        }
ex.message shouldContainIgnoringCase "message"