1

I have a data that I want to mock out that takes val arguments in the constructor.

class DeviceProxy(val context: Context, val name: String) {
    ...
}

Parts of my code check the name to make sure it's what is expected but I can't figure out how to pass a name in when I create the mock and I can't figure out how to mock access to the name property.

I tried:

deviceMock = mock(DeviceProxy::class.java)
whenever(deviceMock.name).thenReturn(TEST_DEVICE_NAME)

but that gives me this error:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

So then I started looking into mockConstructor but I don't know if what I was finding is old or what but none of the examples I saw compiled for me.

I would be happy doing it either way if someone could walk me through making one of these approaches work.

CaseyB
  • 24,780
  • 14
  • 77
  • 112
  • Does this answer your question? [Mocking kotlin property with accessors in Mockito](https://stackoverflow.com/questions/48833937/mocking-kotlin-property-with-accessors-in-mockito) – Silvio Mayolo Nov 09 '22 at 00:49
  • It doesn't. My work locks us down on what we are allowed to do. But I found another way. – CaseyB Nov 10 '22 at 19:35

1 Answers1

0

I am not sure Mockito plays nicely with Kotlin.

If you can switch to alternate framework you'll find mockk is feature-similar to Mockito but is kotlin native. Certainly your use case works with mockk:

import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Test

class DeviceProxy(val context: String, val name: String)

class DeviceTest {
    @Test
    fun test() {
        val mockDevice = mockk<DeviceProxy>()
        every { mockDevice.name }.returns("cheese")
        println(mockDevice.name)
    }
}
AndrewL
  • 2,034
  • 18
  • 18
  • It's also possible to write your tests in Java. Kotlin properties compile to Java methods in a predictable way (hence can be mocked on the Java side as ordinary methods), so while it's less than ideal it *is* possible to limp by thusly. – Silvio Mayolo Nov 09 '22 at 01:36
  • Sadly my work doesn't allow us to use Mockk but I found a way to make this work. – CaseyB Nov 10 '22 at 19:34
  • > my work doesn't allow :-( not very progressive... best tools for the job and all that. Also it is only in the test scope, so it doesn't change the main code line. So at least post an answer yourself of how you achieved a solution to your own Question – AndrewL Nov 11 '22 at 10:02