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.