Json parser using Kotlin Data Class correctly returns json data, but why does unit testing of parser (MockK) fail?

Viewed 633

I have a very simple JSON parser that uses Kotlin data class, and it works perfectly. However, when I try to unit test the parser method (MockK), assertion fails as the model object returns NULL values. I am new to both Kotlin and MockK, so please help me identify where I am going wrong.

All files/classes used for the purpose are given below:

data.json {"name":"john","age":22,"subject":"engineering"}

parser.kt

interface Parser {
    fun parseJson(jsonObject: JSONObject)
}

Student.kt

data class Student(
    var name: String? = null,
    var age: Int? = null,
    var subject: String? = null
) : Parser {

    override fun parseJson(jsonObject: JSONObject) {
        jsonObject?.let {
            name = it.getString("name")
            age = it.getInt("age")
            subject = it.getString("subject")
        }
    }
}

MainActivity - a simple method to read from data.json, parse it and log results

private fun readJson() {
    val inputStream = (assets.open("data.json"))
    val buffer = ByteArray(inputStream.available())
    inputStream.read(buffer)
    inputStream.close()
    val jsonData = JSONObject(String(buffer, StandardCharsets.UTF_8))

    val student = Student()
    student.parseJson(jsonData)
    Log.d("TAG", student.name + " " + student.age + " " + student.subject) // RETURNS CORRECT DATA
}

StudentTest.kt

class StudentTest {
    private lateinit var student: Student

    @Before
    fun setUp() {
        MockKAnnotations.init(this, relaxed = true)
        student = Student()
    }

    @Test
    fun `test parser`() {
        student.parseJson(JSONObject(DATA))
        assertEquals("mary", student.name) // ASSERTION FAILS - student.name returns NULL
    }

    private companion object {
        const val DATA = "{\"name\":\"mary\",\"age\":21,\"subject\":\"history\"}"
    }
}

Any help will be appreciated. Thanks all in advance.

1 Answers

It appears you don't actually need mocking for this test. Unless your code in your question is incomplete.

Simplified example:

@Test
fun `test parser`() {
    val student = Student()
    student.parseJson(JSONObject("{\"name\":\"mary\",\"age\":21,\"subject\":\"history\"}"))
    assertEquals("mary", student.name)
}

This asserts on name, just as your example. You create an instance of Student and then call parseJson with your unserializable string. The assertion is successful.

If this does not answer your question please rephrase and/or add a better example. :)

Related