Kotlin测试:在参数化测试中有条件地断言抛出异常

问题描述 投票:0回答:1

我想在Kotlin中编写参数化测试。根据输入参数,被测试的函数应引发自定义异常,或者如果一切正常,则应成功。我正在使用JUnit Jupiter 5.3.2。

这是我现在所拥有的简化版本(实际上有多个输入参数)。它可以工作,但是感觉有点难看,因为我需要两次包含经过测试的方法调用:

companion object {
      @JvmStatic
      fun paramSource(): Stream<Arguments> = Stream.of(
            Arguments.of(1, true),
            Arguments.of(2, false),
            Arguments.of(3, true)
      )
}

@ParameterizedTest
@MethodSource("paramSource")
open fun testMyServiceMethod(param: Int, shouldThrow: Boolean) {

      if (!shouldThrow) {
          // here the exception should not be thrown, so test will fail if it will be thrown
          myService.myMethodThrowingException(param)
      } else {
          assertThrows<MyCustomException>{
              myService.myMethodThrowingException(param)
          }
      }
}

是否有更好的方法?

testing kotlin syntax junit5
1个回答
0
投票

您可以轻松地封装它:

inline fun <reified E : Exception> assertThrowsIf(shouldThrow: Boolean, block: () -> Unit) {
    if (!shouldThrow) {
        block()
    } else {
        assertThrows<E>(block)
    }
}

用法:

@ParameterizedTest
@MethodSource("paramSource")
open fun testMyServiceMethod(param: Int, shouldThrow: Boolean) {
    assertThrowsIf<MyCustomException>(shouldThrow) {
        myService.myMethodThrowingException(param)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.