Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a private property

Tags:

kotlin

mockk

Lets say we have a class like this:

class Whatever {
    private var something = false

    fun aMethod(): Int {
        return if( something ) {
            1
        } else {
            0
        }
    }
}

According to the documentation, it looks like I should be able to do the following:

val classUnderTest = spyk(Whatever())

every { classUnderTest getProperty "something" } returns true

assertThat(classUnderTest.aMethod()).isEqualTo(1)

but instead I get the error: io.mockk.MockKException: Missing calls inside every { ... } block

I'm using mockk 1.8.5, kotlin 1.2.51

like image 660
Jamie Dulaney Avatar asked Jul 13 '18 00:07

Jamie Dulaney


People also ask

How do you mock private property?

Make a protected getter for this private variable, and override it in testing subclass to return a mock object instead of the actual private variable. Create a protected factory method for creating ISnapshot object, and override it in testing subclass to return an instance of a mock object instead of the real one.

Can we mock a private class?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.

How do you mock private property in Jasmine?

You can just specify the type of appHttpMock as any , to force TypeScript to relax the type check. AFAIK, you can also use jasmine. createSpyObj() to create the whole mock object, and pretend that the result is an AppHttpMockService: let appHttpMock = jasmine.


1 Answers

Try to use answers instead of returns, like this:

val mock = spyk(MockCls(), recordPrivateCalls = true)

every { mock.property } answers { fieldValue }
every { mock getProperty "property" } propertyType Int::class answers { fieldValue + 6 }
every { mock setProperty "property" value any<Int>() } propertyType Int::class answers  { fieldValue += value }
every { mock.property = any() } propertyType Int::class answers {
  fieldValue = value + 1
} andThen {
  fieldValue = value - 1
}
like image 152
Vova Avatar answered Sep 19 '22 11:09

Vova