11

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?

Noam Silverstein
  • 819
  • 2
  • 12
  • 18
  • 1
    I would only test any method that is not automatically generated by the compiler. Otherwise you'd need to test getters/setters which doesn't bring much value if they don't do anything "custom". The test you're suggesting sounds more like testing the integration with the JSON library (i.e., not a unit test) – user2340612 Jun 07 '19 at 08:40
  • 1
    Choose one: either write unit tests that make sense, or waste your time on code coverage constraints fulfillment. – Miha_x64 Jun 07 '19 at 08:43

1 Answers1

13

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.

MarkRobbo
  • 975
  • 1
  • 9
  • 31