Test expected exceptions in Kotlin

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

    Firt steps is to add (expected = YourException::class) in test annotation

    @Test(expected = YourException::class)
    

    Second step is to add this function

    private fun throwException(): Boolean = throw YourException()
    

    Finally you will have something like this:

    @Test(expected = ArithmeticException::class)
    fun `get query error from assets`() {
        //Given
        val error = "ArithmeticException"
    
        //When
        throwException()
        val result =  omg()
    
        //Then
        Assert.assertEquals(result, error)
    }
    private fun throwException(): Boolean = throw ArithmeticException()
    
    0 讨论(0)
  • 2021-02-02 05:28

    org.junit.jupiter.api.Assertions.kt

    /**
     * Example usage:
     * ```kotlin
     * val exception = assertThrows<IllegalArgumentException>("Should throw an Exception") {
     *     throw IllegalArgumentException("Talk to a duck")
     * }
     * assertEquals("Talk to a duck", exception.message)
     * ```
     * @see Assertions.assertThrows
     */
    inline fun <reified T : Throwable> assertThrows(message: String, noinline executable: () -> Unit): T =
            assertThrows({ message }, executable)
    
    0 讨论(0)
  • 2021-02-02 05:29

    Another version of syntaxis using kluent:

    @Test
    fun `should throw ArithmeticException`() {
        invoking {
            val backHole = 1 / 0
        } `should throw` ArithmeticException::class
    }
    
    0 讨论(0)
  • 2021-02-02 05:30

    You can also use generics with kotlin.test package:

    import kotlin.test.assertFailsWith 
    
    @Test
    fun testFunction() {
        assertFailsWith<MyException> {
             // The code that will throw MyException
        }
    }
    
    0 讨论(0)
  • 2021-02-02 05:33

    You can use @Test(expected = ArithmeticException::class) or even better one of Kotlin's library methods like failsWith().

    You can make it even shorter by using reified generics and a helper method like this:

    inline fun <reified T : Throwable> failsWithX(noinline block: () -> Any) {
        kotlin.test.failsWith(javaClass<T>(), block)
    }
    

    And example using the annotation:

    @Test(expected = ArithmeticException::class)
    fun omg() {
    
    }
    
    0 讨论(0)
提交回复
热议问题