在使用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) }
}
但是,我们如何将kotlin中的声明和执行与assertFailsWith
分开?
只需像在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)
}