Is there some way to assert that a function does n...
# atrium
c
Is there some way to assert that a function does not throw?
r
Do you still need such a function? I agree with Kevin that usually such a use case should be handled by the test framework but let me know if you have a different use case and I can help you with a corresponding assertion function
c
In my case I have some test cases that should throw (so I use
assert({ ... }).toThrow<...>()
), but I want to also make it clear for other cases that they should not throw - I can imply that it should succeed by just calling the function, but something like
assert({ ... }).toNotThrow()
makes it really clear what my intention is
(I’m testing an initialiser block that does some validation, so it doesn’t make sense to make an assertion about the return value)
r
In the simplest form you can use the following:
Copy code
fun <T : Throwable> Assert<T>.notToThrow () = this
c
That won’t quite work - if I have a
Throwable
, then it’s already thrown
I need an assertion on a lambda
r
Ah... sorry, I am writing from my phone and did not have the code at hand. Make the above an extension function of: ThrowableThrown.Builder
c
OK, I’ll give that a go
Thanks!
r
Wait... I am pretty sure you need to check that exception is null
It's a bit cumbersome on the phone, I'll check it later. Also notice that my slack notifications seem to be broken. Did not get any notice about your question or this reply.
I guess it's a bit more complicated than I wrote. In the meantime you could use:
Copy code
fun Assert<() -> Any?>.notToThrow () = subject ()
Btw. good idea, I opened a feature request: https://github.com/robstoll/atrium/issues/53
Here the solution for ThrowableThrownBuilder:
Copy code
fun ThrowableThrown.Builder.notToThrow() = act()
0.8.0-alpha contains a
notToThrow()
function
c
Great, I’ll try that now