jeudi 23 janvier 2020

Kotlin tests: conditionally assert throwing exceptions in parametrized tests

I'd like to write a parametrized test in Kotlin. Depending on input parameters, the tested function should throw custom exception or it should succeed if everything is ok. I'm using JUnit Jupiter 5.3.2.

This is simplified version of what I have now (there are multiple input parameters in fact). It works, but it feels a little ugly as I need to include the tested method call twice:

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)
          }
      }
}

Is there any better approach on this?

Aucun commentaire:

Enregistrer un commentaire