Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockk Mocking Private Properties in Kotlin

I have a simple class with a private field.

class EmployeeData {

    private var employeeAge: Int = 0
    
    fun getAge(): Int {
        return 1 + employeeAge
    }
}

I am trying to test this private employeeAge with the following from official docs

@Test
fun testPrivateAge() {

    val mock = spyk(EmployeeData())

    every {
        mock getProperty "employeeAge"
    } propertyType Int::class answers { fieldValue + 6 }
    every {
        mock setProperty "employeeAge" value any<Int>()
    } propertyType Int::class answers  { fieldValue += value }


    every { mock getProperty "employeeAge" } returns 33
    every { mock setProperty "employeeAge" value less(5) } just Runs

    assertEquals(10,mock.getAge())
}

I am receiving such exception from MockK

io.mockk.MockKException: Missing calls inside every { ... } block.

at io.mockk.impl.recording.states.StubbingState.checkMissingCalls(StubbingState.kt:14)
at io.mockk.impl.recording.states.StubbingState.recordingDone(StubbingState.kt:8)

Any clue on what's I am doing wrong? Official docs suggest using such technique against private properties but for me it doesn't work and I'm using latest on this moment version of MockK which is v1.10.0.

Though for private methods it is working like a charm. I am able to test the private method in this logic.

like image 254
user3949888 Avatar asked Oct 15 '22 03:10

user3949888


People also ask

Is MockK better than Mockito?

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.

What is relaxed MockK?

Mocking frameworks supports relaxed mocks like mockk's relaxed. This helps in getting a minimal test setup ready for tests without having to provide mock implementations for all methods of the mocked object.

How do you verify in MockK?

verify supports the same argument matchers as every , along with a few additional matchers. Inside the verification block (between the opening curly bracket { and closing curly bracket } ), you write the method you want to verify.


1 Answers

This is a problem with some Kotlin optimisations. According to MockK author "Brief explanation. It is nearly impossible to mock private properties as they don't have getter methods attached. This is kind of Kotlin optimisation and solution is major change."

More info can be found on these 2 Github issues:

  • https://github.com/mockk/mockk/issues/263
  • https://github.com/mockk/mockk/issues/104
like image 117
Tsuharesu Avatar answered Oct 21 '22 01:10

Tsuharesu