Include setters in objects - only used in unit tests

java, setter, unit-testing

Solution

Yes, it is a bad practice. It's not earth shatteringly bad and sometimes it's the best available option, but still it's bad. In your case the root of the problem i having a state which is private to Java and public to some external JSON files (which could be the lesser of two evils in your case, but does not sound right)

A couple of alternatives (also bad, but in some contexts - maybe bit better) would be:

- make the required fields package-private and access them directly in your tests

- add a constructor to be used only in tests

- DO parse the JSON file for every test; you are not likely to notice any overhead.

Problem

I have a question... Is it bad practice to add setters for variables in an object, if these setters are only used in the unit tests? I have a project where I have some objects that are initialized through parsing a json file with jackson. In the unit tests I've called the setters for the variables instead of always providing a json file. If I parse the json file for each test, this is a bit unnecessary overlay, since I only want to test that the specific objects behave as expected for given values.

Original source