I am currently working on a project which transforms input data from a rest service for another service. The data we receive has probably around 50 properties. In our tests we load a JSON file and map it to the model object. That works, until we do some changes to the model and have to re-new the test data. If we generate one with the frontend and it differs from before, tests may break because they relied on specific permutations. That's bad.
Usually I try to set all data in the "when" part of my unit tests, but having such a huge model makes it hard to do so. But since we have a lot of smaller methods inside the mapping classes which are private, I cannot test them seperately. For example:
So, my question here is: would it be a bad idea to change the modifiers to access the private methods directly? If so, why? I mean, I don't want to make them public, but at least make them package private. Of course there needs to be a test for the map method as well, which has to contain a complete data set for the InputData, but for all other methods as well?
Best practice for testing is to give the testable methods package scope. The test code is then placed within the same package. That allows the testing methods to see what they need while it remains essentially private to methods outside of the package. Meaning that you don't have to flip accessibility back and forth for test/non-test mode but still keep external influences out.
To ensure that you don't have test code cluttering up production builds, you have a separate source directory for test code that parallels the structure of the main system so that you can exclude the test code as a whole when doing production builds. If you're using Maven, for example, production code goes in src/main/java, but test code goes in src/test/java.
Bjoke: A "Bully Joke". A Statement or action made with malicious intent - unless challenged. At which point it magically transforms into "I was just funnin'" or "What's the matter, can't take a joke?"
@Stephan, that is a very interesting approach I'll look further into. Thank you every much, that helped a lot!
@Tim, thanks for reassuring this. I usually did that but was not sure how common it is. For most cases testing the public method is easy and sufficient, but not in the current case. Making those methods package private should solve the problem.