Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing classes through other test classes

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?

like image 223
jordan Avatar asked Apr 25 '14 00:04

jordan


People also ask

Can a unit test test multiple classes?

A test can exercise methods from three objects and still be a unit test. Some may claim that's integration but three lines of code are just as "integrated" so that's not really a thing. Method and object boundaries don't present any significant barrier to testing.

Which testing is used for unit testing?

White box testing approach used for unit testing and usually done by the developers.

Can unit testing be performed parallel to coding?

Unit Testing is the type of software testing level in which each individual component of the software is tested. Unit Testing is generally performed by the developer. Unit Testing can't be used for those systems which have a lot of interdependence between different modules. It does not allow for parallel testing.


1 Answers

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.

like image 186
Mark Seemann Avatar answered Oct 02 '22 12:10

Mark Seemann