@MockK or mockk()
Solution 1:
From MockK project
No there is no difference between the two implementations, they are equivalent.
Generally speaking, you can use mockk() when you need to declare mocks dynamically in your code, or if you need, for instance, just a single mock to have its unit functions relaxed (in which case you would build it with mockk(relaxUnitFun = true).
If your mocks have all the same behavior, you can use the annotations version.
Solution 2:
I'd recommend using mockk()
and "naive" constructor dependencies injection in tests rather than annotations because of these two reasons:
-
The
mockk()
builder allows you to define immutable variables withval
which is more safe, efficient & better* (in terms of software development at all), whereas with@Mockk
you should usevar
keyword; -
@InjectMockKs
is not that cool as it seems. I worked on a project where I caught the same issue that Mockito has. My teammate removed one of the class dependencies somewhere in a middle of the constuctor arguments, built & ran the code, but forgot to fix & run tests locally. He pushed those changes, but then we got an error in our "Run Tests" pipeline stage which was pointed to nowhere, just NPE about missing class. We spent some extra time to finally find the issue, the thing is
Mockito will try to inject mocks only either by constructor injection, property injection or setter injection in order and as described below. If any of the following strategy fail, then Mockito won't report failure; i.e. you will have to provide dependencies yourself.
https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/InjectMocks.html