将 mockk 验证与断言库一起使用时检查所有断言和验证

Check all assertion and verifications when using mockk verification together with assertion libraries

我希望测试报告所有断言和验证。因此 mockk 验证 AND 断言库(在本例中,KotlinTest)断言应该 运行 而不是短路。

换句话说,我不希望测试停止...

verify(exactly = 1) { mock.methodcall(any()) } // ... here
success shouldBe true // how can I check this line too

也不...

success shouldBe true // ... here
verify(exactly = 1) { mock.methodcall(any()) }  // how can I check this line too

如何做到这一点?如果我可以同时使用它,我愿意只使用一种工具。

根据您的评论,您说您正在使用 KotlinTest

在 KotlinTest 中,我相信您可以使用 assertSoftly 来实现您想要的行为:

Normally, assertions like shouldBe throw an exception when they fail. But sometimes you want to perform multiple assertions in a test, and would like to see all of the assertions that failed. KotlinTest provides the assertSoftly function for this purpose.

assertSoftly {
  foo shouldBe bar
  foo should contain(baz)
}

If any assertions inside the block failed, the test will continue to run. All failures will be reported in a single exception at the end of the block.

然后,我们可以将您的测试转换为使用 assertSoftly:

assertSoftly {
    success shouldBe true
    shouldNotThrowAny {
        verify(exactly = 1) { mock.methodcall(any()) }
    }
}

有必要将 verify 包裹在 shouldNotThrowAny 中以使 assertSoftly 在它抛出异常时意识到它