I want to write a test case that expects a setter to throw an exception.
class ClassUnderTest {
fun regularMethod(){ require(false)}
var currentValue: Int = 0
set(_) {
require(false)
}
}
For a regular function I can simply do:
import org.amshove.kluent.*
import org.junit.jupiter.api.*
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
class Tests {
@Test
fun `debug throwing fun`() {
val f = ClassUnderTest()
invoking { f.regularMethod() } `should throw` IllegalArgumentException::class
}
}
But for the setter I am a bit confused
@Test
fun `debug throwing setter`() {
val f = ClassUnderTest()
//1) doesn't compile: Expected a value of type Any?
invoking { f.currentValue = 0 } `should throw` IllegalArgumentException::class
//2) works, but why? Is this canonical?
invoking { 0.also { f.currentValue = it } } `should throw` IllegalArgumentException::class
//3 compiles but no exception thrown -> test fails
invoking { { f.currentValue = 0 } } `should throw` IllegalArgumentException::class
}
1) was my intuitive approach. Apparently there is no return value from a setter. Why not? have defined a function which is called, so I would expect the same behavior as a void method.
2) Android Studio suggested this one. Why does this now work? And is this the recommended way?
3) My own attempt, why doesn't this one work?