MockK: Mocking method is better than Mockito in Kotlin

Tram Ho

We all know Mockito is a very useful library in Unit Test. It is the best way to create mockups and use it in Java and Kotlin. But since it is a library built for Java, it has certain limitations when it is used for Kotlin. That is also the reason for the birth of MockK – a mocking framework written entirely in Kotlin and exclusively for Kotlin.

Like Mockito, MockK allows you to create and stub objects within your test code.

Mocking objects allows you to test on independent objects. Any dependency on the test object can be mocked to provide fixed conditions, thus ensuring the tests are always stable and clear.

Mockito is a popular framework used by Java developers and extremely powerful. But it does have a few annoyances when it comes to Kotlin. MockK, specially designed for Kotlin, will give us a much more comfortable experience.

For Kotlin 1.3 and above, we need to declare dependency (Kotlin DSL) for MockK as follows:

The latest version of MockK so far is 1.10.0.

A sample code snippet is:

Now take a look at what this MockK library has in particular.

1. Chained mock:

Final result can be returned by specifying the complete sequence of calls. There is no need to simulate each method output.

Assuming the offer has many different types and its return type is generic, the hint will help provide hints to mock the correct type we need.

2. Mock object:

The cool thing about MockK is that objects can also be mocked.

One interesting thing about mocking an object is that even though the object has only one instance, mockk<Calculator>() can have many different instances. Even enums can be mocked this way.

3. Capturing

Object values ​​/ properties can be captured using a slot or mutableList .

4. Mocking both suspend function:

Mockk also supports mock suspend functions.

5. Mocking both Extension functions

Mocking extension function.

6. Mocking modules:

Since Kotlin allows to write functions directly in the file without declaring any class, in such cases we need to mock the entire file with mockStatic .

7. Mock private function:

MockK makes mocking private methods very easy.

If you want to verify calls to private methods then you need to set recordPrivateCalls=true while creating spy .

8. Even the constructor can be mocked:

Unit testing becomes very frustrating if the original code creates the objects of a class and then executes the function calls in the test target function. It can be solved using mock constructor.

Source: https://medium.com/@prashantspol/mockk-better-to-way-to-mock-in-kotlin-than-mockito-1b659c5232ec

Share the news now

Source : Viblo