Mark
Mark

Reputation: 2148

using json unit test files in a java program

I am trying to unit test some code. I have 2 fields in my input data that may or may not be in the data, so I want to test all 4 scenarios (ab, a not b, b not a, neither a nor b). I created 4 different json files to use as mocked input, covering each scenario. I could have created one file with neither field, and then just added the required field into the mock data for each of the 4 tests. That approach to me, seems like the test has too much control over the test data. I prefer the 4 files approach, but one of my coworkers is complaining about 4 files being almost exactly the same.

I know this is asking for opinion, but which seems like a better approach? Have all 4 files, or have each test manipulate the data before the assertion?

Upvotes: 0

Views: 1035

Answers (1)

Bor Laze
Bor Laze

Reputation: 2506

Like for me, your coworker is right.

Create two files: a.json-part and b.json-part. Let's a.json-part contains

"a": .....

and b.json-part contains similar content for b (NB: not a JSON, just a part!)

So, for your tests you can build test data by simple concatenation of parts like

String ab_json = "{" + readAsText("a.json-part") + "," + readAsText("b.json-part") + "}";
String a_not_b_json = "{" + readAsText("a.json-part") + "}";

and so on.

In this case you can combine your fields as you want and can be sure you didn't miss any file in case if some field is changed.

Upvotes: 1

Related Questions