mardi 16 avril 2019

Testing class by mocking getter

I try to test a class which as two properties with getters where the one getter calls a static method. I want to mock the getter with static method to test the parsing logic of the other getter. The problem is that can't access the variable via the getter and thus calling the mock.

I searched the kotlin documentation for the getters and setters but didn't found a solution.

class ClassToTest() {
    val firstname: String
        get() = this.name.split(" ")[0]

    val fullName: String
        get() = SomeService.getFullName()
}

class ClassToTestTest() {
    fun `firstname should return first part of the name`() {
        val classToTestMock = mock<ClassToTest>()
        `when`(classToTestMock.name).thenReturn("Walter White")
        assertEquals(classToTestMock.firstname, "Walter)
    }
}

I expect to get "Walter" back but instead the ClassToTest.firstName accesses the variable directly and not the mocked getter.

Can someone point me to the right direction? :D

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire