0

我正在尝试使用 Mockito 在 Kotlin 中为所述处理编写异常处理和测试。由于没有抛出异常,测试失败了,我不知道为什么。看起来他们应该被扔掉,我很难过。

这是有问题的代码示例。

private fun tryToDoTheThing(workItem: WorkItem, metrics: Metrics) {
    try {
        serviceFacade.doTheThing(workItem.accountId, workItem.name)
    } catch (ex: Exception) {
        handleException(ex, metrics, workItem)
    }
}

@Throws(DoTheThingFailedException::class)
private fun handleException(ex: Exception, metrics: Metrics, workItem: WorkItem) {
    var message: String
    when (ex) {

        is <other exception cases that are not valid for this question> -> {
            throwTheThingFailedException(message, metrics)
        }

        is RuntimeException -> {
            metrics.addCount(FAULT, 1)
            val cause = ex.cause
            message = "Received exception when attempting to to the thing " +
                    "name=[${workItem.name}], accountId=[${workItem.accountId}]"

            if (cause is HttpFailureException) {
                metrics.addProperty(EXCEPTION, cause!!::class.java.simpleName)
            } else {
                metrics.addProperty(EXCEPTION, ex::class.java.simpleName)
            }
            LOG.info(message)
            throw DoTheThingFailedException(message, ex)
        }
    }
}

@Throws(DoTheThingFailedException::class)
private fun throwAcknowledgeJobFailedException(message: String, metrics: Metrics) {
    LOG.info(message)
    metrics.addCount(ERROR, 1)
    throw DoTheThingFailedException(message)
}

这是测试

@Test(expected = RuntimeException::class)
fun handleRuntimeException() {
    // given        
    val errorMessage = "Received exception when attempting to acknowledge name=[name], accountId=[accountId]"

    `when`(serviceFacade.doTheThing(any(), any())).thenThrow(RuntimeException())

    // when (this calls the item that does the thing)
    val runOneIteration = WorkDispatcher::class.java.getDeclaredMethod("runOneIteration")
    runOneIteration.invoke(workDispatcher)

    // then
    verify(metrics).addCount(FAULT, 1)
    verify(metrics).addProperty(EXCEPTION, "RuntimeException")
}

我还尝试了在此测试中抛出异常的变体,包括

whenever(serviceFacade.doTheThing(any(), any())).doAnswer { throw RuntimeException(errorMessage) }

whenever(serviceFacade.doTheThing(any(), any())).doThrow(RuntimeException(errorMessage))

即使我添加了一个验证异常是运行时异常的 println 语句,在日志消息之后,异常打印但它仍然给我以下结果:

[junit] Testcase: handleRuntimeException(com.abc.def.packageName.WorkDispatcherTest):   FAILED
[junit] Expected exception: java.lang.RuntimeException
[junit] junit.framework.AssertionFailedError: Expected exception: java.lang.RuntimeException
4

0 回答 0