Testing Inheritance
Not sure you get the whole inheritance idea? Still not sure which fields and methods get inherited and which are overridden? Looking to test your understanding?
Knowing what we know now about Unit Testing and Inheritance , we can test that our subclasses extend their base classes.
We can add a CatTests
project to our Cats
solution and write some code to ensure that HouseCat
inherits what we expect it to.
|
|
Here, we’re testing that one of our HouseCat
constructors will call the Cat constructor and appropriately assign the HouseCat
object’s weight
field. Remember, we don’t need to write unit tests for getters or setters unless they do something extra in addition to getting or setting the field. The purpose of this test, though, is less to test getting keyboardCat.Weight
and more to validate that the subclass constructor has inherited the base class constructor.
It’s a good practice to test your subclasses to verify the items that they inherit or override.
Check Your Understanding
Fill in the blank to test that the no-argument constructor of Cat is called when the second constructor on HouseCat is used?
Second HouseCat constructor:
|
|
|
|
Assert.AreEqual(13, keyboardCat.Weight);
Assert.IsNotNull(keyboardCat.Weight);
Assert.AreEqual(13, keyboardCat.Weight, .001);
Assert.IsNotNull(keyboardCat.weight);
What additional assert method can we add to this test to properly verify that HouseCat
inherits Eat()
?
|
|
Assert.IsFalse(keyboardCat.Tired);
Assert.IsTrue(keyboardCat.Tired);
Assert.IsTrue(keyboardCat.Hungry);
Assert.IsFalse(keyboardCat.tired);