Search code examples
androidunit-testingkotlinjunit4mockk

what's the difference between @Mockk and mockk<*>()?


In this Q&A, it says there's no difference. And some people says annotation is better or using constructor(mockk<*>()) is better.

For me, if they are equivalent, less line of code(not using annotation) is better.

Many sample code shows @MockK is used for the values that pass to Class such as ViewModel/Activity or Fragment. On the other hand, mockk<*>() is used for the classes that have its behaviour or data class, etc

There must be some differences since one is annotation and the other is using constructor. And there must be some reasons why each of them are created, not only one of them.

If you know this, could you please answer it?


Solution

  • Hi, 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.

    from https://github.com/mockk/mockk/issues/559