Becca
Becca

Reputation: 1580

Unit testing complex logic

What is the best way to unit test a relatively complex method where the test for each post-condition is very similar to the tests for the other post-conditions? The pre-conditions are easy to test in isolation, but a lot of setup goes into making sure that they all hold so that the post-conditions can be tested. The three ways that I've thought up are:

  1. Create a general function that can test everything at once, but defaults to the simplest possible scenario. This function would take flag parameters indicating the deviations from the simplest scenario. Then, create a unit test for each post-condition (or combination) that calls that function with the appropriate flags to get coverage of that post-condition. The benefits here are that there is almost no code duplication, so if the code being tested changes, only one test function needs to be rewritten; and that it is trivial to write the test to cover groups of post-conditions, but the drawback is that the general test function is very complex
  2. Make a unit test for the simplest scenario, then copy, paste, and modify. The benefit is that each test is very simple. The drawback is that a problem with the original test will need to be fixed as many times as it is pasted.
  3. Write a general function that allows the various bits and pieces to be overridden by taking functions as parameters, but by default tests the simplest scenario. The benefits are similar to those for the general function with flags, but I think it might be more complicated to make it all mesh together.

The fourth option would be "you're doing it wrong; break the method being tested down into bits that are simpler to test!"

Any ideas?

Upvotes: 0

Views: 1014

Answers (1)

Don Roby
Don Roby

Reputation: 41137

My earlier comment was somewhat in jest.

What I would actually advocate, broadly speaking, is to do what you list as option 2, but then refactor your test code to eliminate the duplication that you created by the copy-modify work.

Once you have this all tested, you might then look for ways to refactor the production code to break it down into smaller and more manageable pieces and make those pieces reusable. But it's always healthy to have tests before making big changes.

Upvotes: 2

Related Questions