Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing inheritance

I have a question concerning unit testing. Let's say that I have several classes that inherit behaviour from a parent class. I don't want to test all the child classes for this behaviour. Instead I would test the parent class. However, I should also provide a test proving that the behaviour is available in the child classes. Do you think something like Assert.IsTrue(new ChildClass() is ParentClass) makes sense?

like image 213
trendl Avatar asked Feb 12 '09 12:02

trendl


People also ask

What is test inheritance?

Inheritance definitionInheritance in OOP is achieved when one object acquires (inherits) the properties and the behaviors of the parent object. This means that the protected and public members of the parent class can be reused in the derived class, without having to define them all over again.

How do you unit test a class that extends a base class?

If you really need to extend the base class to override something, extract the functionality to a third class and make the extended class a proxy. The extended class does nothing else than call methods on the third class. E.g. This way, you can test the real implementation, without instantiating the base class.

Where inheritance should not be used in Java?

Multiple class inheritance is not allowed in Java. Whereas multiple interface implementation is allowed. One class extension and multiple interface implementation is allowed. Also inheritance usually cause you to break the equality contract.

Should you unit test middleware?

There should be at least two unit test to ensure that middleware is functioning as expected: If incoming request does not have cookie, it would be added to response. If incoming request had the cookie, no cookie would be set in response.


1 Answers

If you're using a state-of-the-art unit-testing framework, I don't understand the statement

I don't want to test all the child classes for this behaviour.

Your unit tests (written against an instance of the parent class) should work unchanged if you hand them an instance of a child class, provided that your child class hasn't overridden some aspect of the parent's behavior in a way that breaks the contract on the inherited methods. And that's exactly what you need to be testing, isn't it?

If you're concerned about the time it takes to run the tests, I'd double-check to make sure that your tests are partitioned such that you can selectively run tests based on what you're actively working on (but still run the full portfolio periodically to catch unintended dependencies.)

like image 194
joel.neely Avatar answered Sep 19 '22 13:09

joel.neely