Kluent
Kluent copied to clipboard
Add function reference support for use with shouldThrow
As an alternative syntax to:
val theFunction = { myThrowingFunction() }
// Expect any exception
theFunction shouldThrow AnyException
It would be really nice to add function reference syntax such as:
::myThrowingFunction shouldThrow AnyException
If the function takes in an argument it would then be:
::myThrowingFunction providedWith "some argument" shouldThrow AnyException
I've hacked these implementations in my own project as:
fun <R: Throwable> KFunction0<R>.shouldThrow(expectedException: KClass<R>) {
val f = { this }
f.shouldThrow(expectedException)
}
infix fun <P1, R> KFunction1<P1, R>.providedWith(arg: P1): () -> Any? = {
this.invoke(arg)
}
I would be happy to clean it up, and submit a formal PR if this sort of feature interests you.
Thanks!
An alternate, simpler approach could be to introduce a wrapper function that returns a lambda for use with shouldThrow
.
For example:
invoking { myThrowingFunction() } shouldThrow AnyException
fun invoking(f: () -> Unit): () -> Unit = f
I guess ultimately what I'm trying to avoid is having to define a local interim variable that is then passed to shouldThrow
. I think one of these two approaches would avoid some of the variable noise in tests.
I really like that idea, as it reduces the noise in tests.
Can the providedWith
function work with an arbitrary number of parameters?
If not I would prever the second version.
The second version also doesn't abstract away the function call which makes it a bit clearer what is tested.
If you like, send a PR 👍