Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate default values for a data class / POJO (in Kotlin/Java)?

Tags:

java

kotlin

Remark: I ask it in Kotlin, but it applies to Java too.

For example, I have a POJO / data class:

data class Example(
    val someInt: Int,
    val someString: String,
    val someObject: Any,
    ... say it has 10 fields ...
)

I need to pass it to some code in my tests, and that particular code only cares about the someString field. Therefore, I hope I do not need to care about those other fields and just fill them with garbage (possibly just things like 0 and ""). Also, I do not want to use default values for the constructor, because for normal business code that field should be required, and it is only in test code that I want to fill dummy value.

Thus, I wonder how to generate default values for a data class / POJO (in Kotlin/Java)?

My naive thoughts: Use reflection and call the constructor. But I hope there already exist a library, or there is a simpler solution. Thanks!

EDIT

About why I need this: In the old days when using Java POJO, I can solve this problem by making the Example class like

class Example {
  int someInt;
  String someString;
  ...
}

Then I use it like

new Example()
  .setSomeInt(42)
  .setSomeString("hello")
  // I do not care about all other fields in this specific test case, so I just leave them null

But in kotlin, the idiomatic approach is to define the data class as the code example at the beginning of this question. Then, we see that (1) fields are final (2) not nullable. Then the old approach cannot work.

like image 356
ch271828n Avatar asked Oct 23 '25 00:10

ch271828n


1 Answers

You just have to initialize the data objects with some defaults in the setup code of your tests. One wonders why their values would not matter. Maybe this in itself is an indication that the code is not designed well.

If some fields truly don't matter for the test, just pass null or 0 or "" (of whatever simple default is applicable).

To avoid duplication you can set up a method for this that you use throughout your test.

like image 180
Adriaan Koster Avatar answered Oct 24 '25 15:10

Adriaan Koster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!