Question

Suppose I am using TDD to create some class A. After I am done and have a "green" bar, I decide that I want to extract some class B with only static methods from class A using some refactoring tool. I now have class A and class B both fully unit tested, but only through the test class for class A. Should I also now create a test class specific to functionality of class B, even though that would be duplicating test?

Was it helpful?

Solution

As always, it depends on your context. What do you care about?

Overall behaviour

If you're building a system for internal use, or even a public (web) service, where the software you're shipping is the entire system, you don't have to care too much about a single class. If you're building a system, then test the system.

As long as it's covered by tests, you know that your system behaves correctly. However, you may run into a situation that after some months, you realize that you no longer need the original A class, so you delete it and its corresponding unit tests. This may cause test coverage of B to drop, so it may be a good idea to keep an eye on code coverage trends.

Unit behaviour

If you're building a (class) library, or framework, you're shipping each public class as part of the product. If you have multiple users of your library, you'll need to start thinking about how to avoid breaking changes.

One of the most effective ways to avoid breaking changes is to cover each class by unit tests. As long as you don't change the tests, you know that breaking changes are unlikely if all tests are green. However, that requires that you test all your public classes and members.

Thus, if you extract B to a public class, it's now a class that other consumers may depend on, and it would be a breaking change if you change it. Therefore, you should cover it with new tests. If you're building a unit, then test the unit.

OTHER TIPS

From what you have described the answer is to create another new test. If either changes by you (or someone else who is not familiar with the "shared test") the other class will in no longer be tested.

If this seems wasteful, put the common test code in a third class...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top