developer tip

Kotlin에서 예상되는 예외 테스트

copycodes 2021. 1. 9. 10:13
반응형

Kotlin에서 예상되는 예외 테스트


Java에서 프로그래머는 다음과 같이 JUnit 테스트 케이스에 대해 예상되는 예외를 지정할 수 있습니다.

@Test(expected = ArithmeticException.class)
public void omg()
{
    int blackHole = 1 / 0;
}

Kotlin에서 어떻게해야하나요? 두 가지 구문 변형을 시도했지만 모두 작동하지 않았습니다.

import org.junit.Test as test

// ...

test(expected = ArithmeticException) fun omg()
    Please specify constructor invocation;
    classifier 'ArithmeticException' does not have a companion object

test(expected = ArithmeticException.class) fun omg()
                           name expected ^
                                           ^ expected ')'

구문은 간단합니다.

@Test(expected = ArithmeticException::class)

Kotlin에는 이러한 종류 의 단위 테스트 를 수행하는 데 도움이되는 자체 테스트 도우미 패키지 가 있습니다. 더하다

import kotlin.test.*

그리고 테스트는 다음과 같이 사용하여 매우 표현할 수 있습니다 assertFailWith.

@Test
fun test_arithmethic() {
    assertFailsWith(ArithmeticException::class) {
        omg()
    }
}

kotlin-test.jar클래스 경로에 있는지 확인하십시오 .


@Test(expected = ArithmeticException::class).NET과 같은 Kotlin의 라이브러리 메소드 중 하나를 사용 하거나 더 나은 방법을 사용할 수 있습니다 failsWith().

수정 된 제네릭과 다음과 같은 도우미 메서드를 사용하여 더 짧게 만들 수 있습니다.

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

그리고 주석을 사용한 예 :

@Test(expected = ArithmeticException::class)
fun omg() {

}

이를 위해 KotlinTest사용할 수 있습니다 .

테스트에서 shouldThrow 블록으로 임의 코드를 래핑 할 수 있습니다.

shouldThrow<ArithmeticException> {
  // code in here that you expect to throw a ArithmeticException
}

You can also use generics with kotlin.test package:

import kotlin.test.assertFailsWith 

@Test
fun testFunction() {
    assertFailsWith<MyException> {
         // The code that will throw MyException
    }
}

JUnit 5.1 has kotlin support built in.

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

class MyTests {
    @Test
    fun `division by zero -- should throw ArithmeticException`() {
        assertThrows<ArithmeticException> {  1 / 0 }
    }
}

ReferenceURL : https://stackoverflow.com/questions/30331806/test-expected-exceptions-in-kotlin

반응형