Test expected exceptions in Kotlin

后端 未结 11 806
我寻月下人不归
我寻月下人不归 2021-02-02 04:45

In Java, the programmer can specify expected exceptions for JUnit test cases like this:

@Test(expected = ArithmeticException.class)
public void omg()
{
    int bl         


        
11条回答
  •  鱼传尺愫
    2021-02-02 05:22

    Assert extension that verifies the exception class and also if the error message match.

    inline fun  assertThrows(runnable: () -> Any?, message: String?) {
    try {
        runnable.invoke()
    } catch (e: Throwable) {
        if (e is T) {
            message?.let {
                Assert.assertEquals(it, "${e.message}")
            }
            return
        }
        Assert.fail("expected ${T::class.qualifiedName} but caught " +
                "${e::class.qualifiedName} instead")
    }
    Assert.fail("expected ${T::class.qualifiedName}")
    

    }

    for example:

    assertThrows({
            throw IllegalStateException("fake error message")
        }, "fake error message")
    

提交回复
热议问题