在带有 JUnit5 的 Kotlin 中,我们可以使用 assertFailsWith
在带有 JUnit5 的 Java 中,您可以使用 assertThrows
在 Java 中,如果我想 将可执行文件的声明与执行本身分开 ,为了阐明 Given-Then-When 形式的测试,我们可以使用 JUnit5 assertThrows
像这样:
@Test
@DisplayName("display() with wrong argument command should fail" )
void displayWithWrongArgument() {
// Given a wrong argument
String arg = "FAKE_ID"
// When we call display() with the wrong argument
Executable exec = () -> sut.display(arg);
// Then it should throw an IllegalArgumentException
assertThrows(IllegalArgumentException.class, exec);
}
在 Kotlin 中我们可以使用
assertFailsWith
:@Test
fun `display() with wrong argument command should fail`() {
// Given a wrong argument
val arg = "FAKE_ID"
// When we call display() with the wrong argument
// ***executable declaration should go here ***
// Then it should throw an IllegalArgumentException
assertFailsWith<CrudException> { sut.display(arg) }
}
但是,我们如何使用
assertFailsWith
在 Kotlin 中分离声明和执行?
最佳答案
只需像在 Java 中一样声明一个变量:
@Test
fun `display() with wrong argument command should fail`() {
// Given a wrong argument
val arg = "FAKE_ID"
// When we call display() with the wrong argument
val block: () -> Unit = { sut.display(arg) }
// Then it should throw an IllegalArgumentException
assertFailsWith<CrudException>(block = block)
}
关于exception - Kotlin 和 JUnit 5 断言抛出异常 : separate declaration and execution with assertFailsWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878003/