Mock companion object function


#1

I’m trying to unit test a method with a call to a static method which looks like this

fun methodToTest(): (Context) -> Unit = { context: Context ->
      // something
      ...
      val myFragment = myFragment.getInstance(dataForMethod)
      ...
      // something else
}

To create the Fragment I offer a way that formerly (when the MyFragment class was written in java) was a public static method, now converting MyFragment to Kotlin it became a function in a companion object

This is quite hard to test with either Mockito or Powermockito and I would like to hear advises from the community on how to better address this problem (to know how to test but also if it’s right to use companion object in this case)


#2

Take a look at jMockIt instead of Mockito/Powermockito. I’ve had a lot better luck with it and Kotlin.

I was able to mock a Java static function (slf4j LoggerFactory) without any issues. With Powermock/ito, I had a bytecode issue that I wasn’t able to fix (probably could have with more time, but it seemed like it was going to continue happening - https://github.com/powermock/powermock/issues/779.

There are some Kotlin annoyances with jMockIt, for example I couldn’t get single invocation parameter capture to work, so I had to use the multiple invocation version (where you get a list of values that were passed, 1 for each invocation, even though you only had 1 invocation).

Anyway, give it a try.