https://kotlinlang.org logo
#atrium
Title
# atrium
c

charleskorn

12/08/2018, 9:43 PM
Is there some way to assert that a function does not throw?
r

robstoll

12/09/2018, 8:14 PM
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

charleskorn

12/09/2018, 10:16 PM
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

robstoll

12/11/2018, 3:50 PM
In the simplest form you can use the following:
Copy code
fun <T : Throwable> Assert<T>.notToThrow () = this
c

charleskorn

12/11/2018, 3:53 PM
That won’t quite work - if I have a
Throwable
, then it’s already thrown
I need an assertion on a lambda
r

robstoll

12/11/2018, 3:56 PM
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

charleskorn

12/11/2018, 3:57 PM
OK, I’ll give that a go
Thanks!
r

robstoll

12/11/2018, 3:59 PM
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

charleskorn

01/20/2019, 1:05 AM
Great, I’ll try that now
8 Views