How can Mockito mock a Kotlin `use` (aka try-with-resource)? - kotlin

If I were trying to add mocks to the following code (where the MyTypeBuilder is mocked to return a mocked MyType - which implements Closeable):
myTypeBuilder.build(myTypeConfiguration).use { myType ->
myType.callMyMethod()
}
Then trying to verify interactions with myType.callMethod() something like:
myType: MyType = mock()
myTypeBuilder: MyTypeBuilder = mock()
whenever(myTypeBuilder.build(any())).thenReturn(myType)
doMethodCall()
verify(myType, times(1)).callMyMethod()
I'm getting errors:
Wanted but not invoked:
myType.callMethod()
-> at package.me.MyType.callMyMethod(MyType.kt:123)
However, there was exactly 1 interaction with this mock:
myType.close()
-> at kotlin.io.CloseableKt.closeFinally(Closeable.kt:57)
So it appears that I need to add a whenever to execute the use block, but I'm not sure what that should look like. Alternatively, the use should act like a Mockito spy rather than a mock, but then allow mocking on the other methods.

I tried to reconstruct the error by writing the following code which is basically what you wrote in your question plus some println statements and some boilerplate to make it runnable:
import org.junit.jupiter.api.Test
import org.mockito.Mockito.*
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import java.io.Closeable
open class MyTypeBuilder {
open fun build(config: Any): MyType {
println("build")
return MyType()
}
}
open class MyType : Closeable {
fun callMyMethod() {
println("callMyMethod")
}
override fun close() {
println("close")
}
}
val myTypeConfiguration: Any = "heyho"
fun call(myTypeBuilder: MyTypeBuilder) {
myTypeBuilder.build(myTypeConfiguration).use { myType ->
println("call")
myType.callMyMethod()
}
}
class MockAndUseTest {
#Test
fun test() {
val myType: MyType = mock()
val myTypeBuilder: MyTypeBuilder = mock()
whenever(myTypeBuilder.build(any())).thenReturn(myType)
call(myTypeBuilder)
verify(myType, times(1)).callMyMethod()
}
}
When I run the test case test, it succeeds and is green.
So, unfortunately whatever may cause your problem, it is not contained in the details given by your question.

Related

Equivalent of doReturn(x).when(y)... in mockk?

I am looking for a mockk equivalent of doReturn(...).when(...).*
I am working on writing some unit tests (testing contracts) that involves a lot of system classes and so need to intercept the methods that I don't control and return some call backs (which the method in code would have eventually returned). In mockito, I could do something like doReturn(...).when(...).*
I Wasn't able to find a similar thing in mockK. Seems like every{} always runs the block before answers or returns.
class Vehicle: Listener {
fun displayCar(listener:Listener){
OtherClass().fetchCar(listener)
}
override fun showCarSuccessful() {
//do something
}
}
class OtherClass {
//assume its an outside function that returns nothing but invokes a method of listener call back
fun fetchCar(listener: Listener) {
//... Some system level operations that I don't have control to generate mock objects but in the test I want to use the listener to call some method so that I can
// test some contracts
listener.showCarSuccessful()
}
}
class Tests {
#Test
fun testCarSuccess() {
val listener: Listener = mockk(relaxed = true)
val vehicle = Vehicle()
//also tried with mockkClass and others
val other: OtherClass = mockk(relaxed = true)
every { other.fetchCar(listener) } returns {listener.showCarSuccessful()}
vehicle.displayCar(listener)
//do some verification checks here
}
}
interface Listener {
fun showCarSuccessful()
}
The every{} block is your when clause. You can set up multiple conditions for returning different results. See the example of setting up fixed returns and performing progrommatic answers
import io.mockk.MockKException
import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class MyClass {
fun add(operand1: Int, operand2: Int): Int {
TODO()
}
}
class MockkTest {
#Test
fun testMocking() {
val myClassMock = mockk<MyClass> {
every { add(1, 2) } returns 3 // Set behaviour
every { add(2, 2) } returns 4 // Set behaviour
every { add(3, 4)} answers {args[0] as Int * args[1] as Int} // Programmatic behaviour
}
Assertions.assertEquals(3, myClassMock.add(1, 2))
Assertions.assertEquals(4, myClassMock.add(2, 2))
Assertions.assertEquals(12, myClassMock.add(3, 4))
Assertions.assertThrows(MockKException::class.java) {
myClassMock.add(5, 6) // This behaviour has not been set up.
}
}
}
But, in your example in particular, I find this line:
every { other.fetchCar(listener) } returns listener.showCarSuccessful()
very strange. First it is not doing what you think it is doing - it is going to make that call as you set this behaviour up you are telling your mock to return the result of that call, not to do that cal. To do what you want to do, you should rather do this:
every { other.fetchCar(listener) } answers {listener.showCarSuccessful()}
But even then, this line is setting up the mock behaviour after you have called your class under test - set up your mock behaviour first.
Also, it is strange that you are setting up side effects in a top level mock in a nested mock. Surely for testing your Vehicle class all you want to do is verify that its inner class was called with the correct arguments. Also, how does Vehicle get a reference to your OtherClass mock, it is instantiating a new one and calling that function.
Here is an attempt to make your example work:
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.Test
interface Listener {
fun showCarSuccessful()
}
class Vehicle(val other: OtherClass) : Listener {
fun displayCar(listener: Listener) {
other.fetchCar(listener)
}
override fun showCarSuccessful() {
//do something
}
}
class OtherClass {
//assume its an outside function that returns nothing but invokes a method of listener call back
fun fetchCar(listener: Listener) {
}
}
class VehicleTest{
#Test
fun testDisplayCar(){
val listener: Listener = mockk(relaxed = true)
val other: OtherClass = mockk(relaxed = true) //also tried with mockkClass and others
val vehicle = Vehicle(other)
vehicle.displayCar(listener)
verify{ other.fetchCar(listener) }
}
}
Even this I think is maybe still a bit off - I suspect that the listener you want Vehicle to pass to OtherClass is itself, not an argument...
You should also then write a separate test for OtherClass to make sure it does what you expect it to when you call fetchCar

How to mock and verify Lambda expression in Kotlin?

In Kotlin (and Java 8) we can use Lambda expression to remove boilerplate callback interface. For example,
data class Profile(val name: String)
interface ProfileCallback {
fun onSuccess(profile: Profile)
}
class ProfileRepository(val callback: ProfileCallback) {
fun getProfile() {
// do calculation
callback.onSuccess(Profile("name"))
}
}
We can change remove ProfileCallback and change it into Kotlin's Lambda:
class ProfileRepository(val callback: (Profile) -> Unit) {
fun getProfile() {
// do calculation
callback(Profile("name"))
}
}
This works fine, but I'm not sure how to mock and then verify that function. I have
tried using Mockito like this
#Mock
lateinit var profileCallback: (Profile) -> Unit
#Test
fun test() {
// this wouldn't work
Mockito.verify(profileCallback).invoke(any())
}
but it throw an Exception:
org.mockito.exceptions.base.MockitoException: ClassCastException
occurred while creating the mockito mock : class to mock :
'kotlin.jvm.functions.Function1', loaded by classloader :
'sun.misc.Launcher$AppClassLoader#7852e922'
How to mock and verify Lambda expression in Kotlin? Is it even possible?
Here is example how you can achieve that using mockito-kotlin:
Given repository class
class ProfileRepository(val callback: (Int) -> Unit) {
fun getProfile() {
// do calculation
callback(1)
}
}
Using mockito-kotlin lib - you can write test mocking lambdas like this:
#Test
fun test() {
val callbackMock: (Int) -> Unit = mock()
val profileRepository = ProfileRepository(callbackMock)
profileRepository.getProfile()
argumentCaptor<Int>().apply {
verify(callbackMock, times(1)).invoke(capture())
assertEquals(1, firstValue)
}
}

Dynamic proxy for suspend methods?

This is my interface:
interface BlogService {
suspend fun tag() : JsonObject
}
Is it possible to create a dynamic proxy for the suspend method and run coroutine inside?
I can't use "Proxy.newProxyInstance" from jdk because I get a compilation error (suspend function should be run from another suspend function)
I had the same problem. And I think the answer is Yes. Here's what I figured out.
The following interface
interface IService {
suspend fun hello(arg: String): Int
}
is compiled into this
interface IService {
fun hello(var1: String, var2: Continuation<Int>) : Any
}
after compilation, there's no difference between a normal function and a suspend
function, except that the latter one has an additional argument of type
Continuation. Just return COROUTINE_SUSPENDED in the delegated
InvocationHandler.invoke if you actually want it supended.
Here's an example of creating an ISerivce instance via the java dynamic proxy
facility Proxy.newProxyInstance
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
import kotlin.coroutines.Continuation
import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
import kotlin.coroutines.resume
fun getServiceDynamic(): IService {
val proxy = InvocationHandler { _, method, args ->
val lastArg = args?.lastOrNull()
if (lastArg is Continuation<*>) {
val cont = lastArg as Continuation<Int>
val argsButLast = args.take(args.size - 1)
doSomethingWith(method, argsButLast, onComplete = { result: Int ->
cont.resume(result)
})
COROUTINE_SUSPENDED
} else {
0
}
}
return Proxy.newProxyInstance(
proxy.javaClass.classLoader,
arrayOf(IService::class.java),
proxy
) as IService
}
I believe this code snippet is simple enough and self-explaining.

Is there a way to verify that a top-level function passed as a dependency to a class has been called during testing?

I have a class that receives a function allowing it to display things on the UI during a failure case. What's the best way that I can verify that the function is called in my test?
MyClass(private val uiPrinter: (String) -> Unit) {
fun foo() {
// do some stuff
uiPrinter("printing from foo!")
// do some more stuff
}
}
MyClassTest() {
val testUiPrinter: (String) -> Unit = { System.out.println(it) }
#Test
fun uiPrinterIsInvoked() {
val myClass = MyClass(testUiPrinter)
myClass.foo()
// can I verify that testUiPrinter has been invoked?
}
}
You may want to check out the Model-View-Presenter architecture. Its purpose is to hide the Android framework behind an abstract View interface which a purely Java Presenter can interact with. In your example:
interface ViewInterface {
fun printError(error: String)
}
class MyPresenter(private val view: ViewInterface) {
fun foo() {
// do some stuff (testable stuff)
view.printError("Printing from foo()!")
// do some more (testable) stuff
}
}
class MyPresenterTest() { // Test using Mockito to mock the abstract view
private val view = mock(ViewInterface::class.java)
private val presenter = MyPresenter(view)
#Test
fun printsError() {
// set up preconditions
presenter.foo()
verify(view).printError("Printing from foo()!")
}
}
Your concrete view will generally be an Android Activity, Fragment, or View which implements the view interface. Notice MyPresenter only expects the abstract view and does not need knowledge of the framework-dependent operations.
class MyActivity : Activity(), ViewInterface {
// ...
override fun printError(error: String) {
textView.text = error // For example
}
// ...
}
This can be achieved by mocking the higher-order function as higher-order functions are objects unless inlined.
#Mock
val testUiPrinter: (String) -> Unit
#Test
fun uiPrinterIsInvoked() {
val myClass = MyClass(testUiPrinter)
myClass.foo()
verify(testUiPrinter).invoke("Printing from foo!")
}

How mock Kotlin extension function in interface?

I have an extension function for interface like the following:
import javax.jms.ConnectionFactory
fun ConnectionFactory.foo() {
println("do some stuff")
}
How can I mock the function foo?
Please note, I have seen approaches for classes and objects in http://mockk.io/#extension-functions, but it does not work. I have tried this one:
import io.mockk.classMockk
import io.mockk.every
import org.junit.Test
import javax.jms.ConnectionFactory
class ExtensionFunctionTest {
#Test
fun mockExtensionFunction() {
val connectionFactory = classMockk(ConnectionFactory::class)
every { connectionFactory.foo() } returns println("do other stuff")
connectionFactory.foo()
}
}
It throws exception:
io.mockk.MockKException: Missing calls inside every { ... } block.
According to the documentation in case of module wide extension functions you need to staticMock "hidden" class created for an extension function.
Here is an example (assuming the file name is com/sample/extmockingtest/SampleTest.kt):
fun <T> Iterable<T>.foo(): String = "do some stuff"
class ExtensionFunctionTest {
#Test
fun mockExtensionFunction() {
val itMock = classMockk(Iterable::class);
staticMockk("com.sample.extmockingtest.SampleTestKt").use {
every {
itMock.foo()
} returns "do other stuff"
assertEquals("do other stuff", itMock.foo())
verify {
itMock.foo()
}
}
}
}