1

I've been writing code that processes certain fields of an object by modifying their values. To test it, I first wrote a JUnit test case that recursively traverses fields of an object and makes sure they're correctly modified. The CUT (Class Under Test) does something vary similar: it recursively traverses fields of an object and modifies them as required.

So the code to recursively traverse the fields remains the same in test case and CUT, and is currently duplicated, which is against DRY. So I have two questions:

1) have you come across such situations in your project? If yes, did you apply DRY, or let such duplication remain as is?

2) if I put this common code in a util method, I will need to write a test case to test that, which would again involve traversing fields recursively. So how can this be solved without adding any duplication?

2 Answers 2

4

You have just hit the ugly mirror testing anti-pattern. If your CUT has a bug, most likely you will copy it to your test case, essentially verifying that a bug is still there.

You must show us some more code, but basically your test case should be much simpler, no for loops, no conditions - just assertions. If your production code does some fancy traversing, reflection, etc. on complicated data structures - create a test Java object and test every field manually in the unit test.

Sign up to request clarification or add additional context in comments.

2 Comments

I've shown similar code here: stackoverflow.com/questions/10749946/… The objects I'm processing are large, so writing a non-recursive JUnit to test them will become quite long. Maybe that's the only way to test it. And you're right about having the same bug in test and CUT. I burnt my fingers with it in this same code.
@shrini1000: looking at your code: yes, create some sample object and do all the assertions manually. This is the right way.
1

Use the visitor pattern to abstract traversing the tree, and then build visitors both in the Test case and in your productive code. And test the Visitor infrastructure separately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.