Closed CarsonRedeye closed 5 years ago
Perhaps anyOrNull() should be constrained to Any?
, not Any
@CarsonRedeye It's a mix of using a non-nullable primitive as an argument in your function (and maybe not having an open class - unless you use inline-mock-maker or allOpen which isn't obvious from your description).
Make your class and method open and also change the signature on the doStuff
function to use a nullable type. Otherwise use the anyInt()
function as your matcher instead of anyOrNull()
.
Here's a working example:
open class Thingy {
open fun doStuff(param: Int?): Boolean {
return false
}
}
@Test
fun failingTest() {
val mock = mock<Thingy>()
whenever(mock.doStuff(anyOrNull())).thenReturn(true)
assertTrue(mock.doStuff(null))
assertTrue(mock.doStuff(1))
}
It's the annoying part of mocking with mockito-kotlin, but it's difficult/impossible to do anything about AFAIK.
I'm aware of that workaround, but I'd rather the test framework deal with this, rather than changing the logic in my actual code to suit the test
@CarsonRedeye But why would you then use anyOrNull()
when you could just use any()
? You have a nonnull parameter in your function, so it would make no sense IMO to use anyOrNull()
. As your method contract says that param
should not be null.
Because I want to be able to write a generic test that accepts any or null, no matter what the parameter. I just want to be able to write anyOrNull() for every parameter when stubbing, without having to continually match it to the actual implementation. It's more of an annoyance that you might think.
This throws a null pointer error, whereas if I replace the
param
with a String it passes. This library is fantastic but this is annoying because I always have to make sure I match any() or anyOrNull() to the actual implementation when I don't actually care about this for the test