Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Mockk a Kotlin top level function?

Tags:

Mockk allows mocking static functions, but how does one mock a Kotlin top level function?

For example, if I have a Kotlin file called HelloWorld.kt, how do I mock the sayHello() function?


HelloWorld.kt

fun sayHello() = "Hello Kotlin!" 
like image 336
Niel de Wet Avatar asked Oct 19 '18 10:10

Niel de Wet


People also ask

What is top level function in Kotlin?

Top-level functions are functions inside a Kotlin package that are defined outside of any class, object, or interface. This means that they are functions you call directly, without the need to create any object or call any class.

What is MockK Kotlin?

In Android, there are a lot of frameworks used for mocking in unit testing, such as PowerMock, Mockito, EasyMock, etc. MockK is definitely a better alternative to other mocking frameworks for Kotlin, the official development language for Android. Its main philosophy is first-class support for Kotlin features.

How do you verify in MockK?

Inside the verification block (between the opening curly bracket { and closing curly bracket } ), you write the method you want to verify. { navigator. navigateTo("Park") } tells MockK to check if the navigateTo method on the navigator object was called with the argument "Park" .

What is relaxed true in MockK?

A relaxed mock is the mock that returns some simple value for all functions. This allows you to skip specifying behavior for each case, while still stubbing things you need. For reference types, chained mocks are returned. Note: relaxed mocking is working badly with generic return types.


Video Answer


2 Answers

There is way to mockk a top level function:

mockkStatic("pkg.FileKt") every { fun() } returns 5 

You just need to know which file this function goes. Check in JAR or stack trace.

like image 194
oleksiyp Avatar answered Sep 21 '22 16:09

oleksiyp


The following syntax has worked to me.

mockkStatic(::sayHello.javaMethod!!.declaringClass.kotlin) 

I'm surprised there is nothing on the jvm-stdlib yet for this.

Edit: This overload has now been introduced officially: https://github.com/mockk/mockk/pull/518

mockkStatic(::sayHello) 
like image 32
gmazzo Avatar answered Sep 18 '22 16:09

gmazzo