Reducing Code Redundancy Between our Test Cases

Learn to reduce test code duplication between your test methods.


Every test case requires the Arrange-Act-Assert steps. Most of the time, arranging data is the same between test methods. If this is the case, you will need to set up your test methods. Test method setup is the process of arranging data once so it may subsequently be used by various test methods.

Demonstrating the problem

Suppose you have an application code that contains a class called HundredMeterSprint. This class stores a list of sprint competitor times. These values represent the time taken to complete a hundred-meter sprint by various athletes. The class has the three following public methods:

  • AverageTime(line 17): This returns the average time taken by all participants to complete the sprint.
  • QuickestTime(line 25): This returns the time taken to complete the sprint by the quickest athlete.
  • LongestTime(line 37): This returns the time taken to complete the sprint by the slowest athlete.

In the test code, we have three test methods that test each of the public HundredMeterSprint methods. Run the tests to ensure they all pass.

Get hands-on with 1200+ tech skills courses.