Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test data class on Kotlin?

I have data class'es in my Kotlin project, what I use for JSON Rest responses.. Example:

data class WeatherResponse(val city: String, val temperature: Double, val humidity: Double)

To fullfill code coverage constraints, I would like to write some tests for above data class.

What unit tests would make sense for Kotlin data classes?

I thought of create a WeatherResponse object and a corresponding JSON String (response from server), parse that String to a WeatherResponse object and compare?

like image 348
Noam Silverstein Avatar asked Jun 07 '19 08:06

Noam Silverstein


People also ask

What is a data class in Kotlin?

It is not unusual to create classes whose main purpose is to hold data. In such classes, some standard functionality and some utility functions are often mechanically derivable from the data. In Kotlin, these are called data classes and are marked with data: data class User(val name: String, val age: Int)

What are the types of testing in Kotlin?

It covers the full range of testing: mock-based unit tests, integration tests, property-based tests, and data-driven tests. In the end, you will be able to write clean and idiomatic tests and apply battle-proven best practices. Check out the details. At the KotlinConf 2018, I held a talk about this topic. You can watch the video here.

What does Kotlin mean?

Answer: Kotlin provides a special type of class called data class, which is usually used for objects that act as a store for data properties and has no business logic or member functions. It provides a lot of advantages with reduced boilerplate code.

How to create a mobile application in Kotlin language?

In kotlin language, we use classes, methods and other pre-defined keywords for to create the mobile-based application. For example, among the Data class is one of the concepts and features for storing and hold the data and state with the help of some standard keywords and methods.


1 Answers

The aim of Kotlin data classes is to avoid boilerplate code and takes the view that if there is no logic in the getters and setters there is no value in typing them out.

Similarly you should not attempt to unit test standard getters and setters if they are automatically generated as you are basically testing the compiler itself which offers no value.

In the case of JSON which you mention, you are effectively testing whatever is serializing your object to JSON. This could have some use if you want to check, for example, specific configuration of this serialization but again I would say you can assume the presence of functionality offered by data classes.

With correct code coverage verification, you should not need to cover lines which don't exist in your Kotlin code. For example, as of 0.8.2 JaCoCo has features which filter out generated code.

like image 178
MarkRobbo Avatar answered Oct 16 '22 14:10

MarkRobbo