I need some advice, I have lot of tests that uses ...
# mockk
h
I need some advice, I have lot of tests that uses
any()
as argument in the
every
part of my tests and then in the
verify
part I checked the exactly value of the argument like this
Copy code
every { car.drive(any()) } returns Outcome.OK

verify(exactly = 1) {
    car.drive(Direction.SOUTH)
}
. I did this because it saves me a lot of typing (and maybe it makes the code more readable as it's shorter) when the argument I'm passing is too long for example: https://gist.github.com/rinnegan/bd8928a750fab4eaebf89652972c7647#file-using-any-L16. So it is okay to write my tests like this? Or do I need to avoid using
any()
and be very explicit and specify the exact argument?
l
Personally, I would always test for the exact case
I don't like any as it allows your test to test multiple scenarios, and IMO it should test only one
You can extract your every to another method, if it's easier to be outside your test
However, I do believe that Mockk will execute your test correctly, even if you're doing it that way, and you might not have any problems with that
You'll have to check what your team agrees with, or what you agree with if you're alone. Both will work
I personally would prefer to not use any, unless testing legacy code
👍 1
d
h
That's a very lengthy article @dave08 I skimmed throught it but I do not understand how is it related to my question
d
Just pointing out that mocks that get messy can sometimes be better written as stubs or other types of test doubles... just because you have a mocking library, it doesn't mean it's always appropriate to use 😉
h
Thanks but I'm still a bit confused @dave08, when is it best to use mock and stub? If it's a function from external library like AWS is it better to mock it or stub it?
d
The rule by me is do what looks the simplist, cleanist, and tests exactly what is needed, not more but certainly not less. If mocks are more complicated or unreadable, just go for a well written stub or other type of test double. Also, in the article, he mentions that mocks create a dependency on the mocked functionality in the tests, which is sometimes required and sometimes makes the tests very vulnurable to change... so some even use mocks sparingly whereas others use them all the time for their advantages. The point is, there are two schools of people and the team has to choose the pros and cons that one is more ready to live with, or make a compromise.