Test expected exceptions in Kotlin

后端 未结 11 800
我寻月下人不归
我寻月下人不归 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

    The Kotlin translation of the Java example for JUnit 4.12 is:

    @Test(expected = ArithmeticException::class)
    fun omg() {
        val blackHole = 1 / 0
    }
    

    However, JUnit 4.13 introduced two assertThrows methods for finer-granular exception scopes:

    @Test
    fun omg() {
        // ...
        assertThrows(ArithmeticException::class.java) {
            val blackHole = 1 / 0
        }
        // ...
    }
    

    Both assertThrows methods return the expected exception for additional assertions:

    @Test
    fun omg() {
        // ...
        val exception = assertThrows(ArithmeticException::class.java) {
            val blackHole = 1 / 0
        }
        assertEquals("/ by zero", exception.message)
        // ...
    }
    

提交回复
热议问题