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.

1
2
3
4
5
6
[TestMethod]
public void InheritsBaseInFirstConstructor()
{
   HouseCat keyboardCat = new HouseCat("Keyboard Cat", 7);
   Assert.AreEqual(7, keyboardCat.Weight, .001);
}

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

Question

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:

14
15
16
17
public HouseCat(string name)
{
   Name = name;
}
1
2
3
4
5
6
[TestMethod]
public void InheritsDefaultCatInSecondConstructor()
{
   HouseCat keyboardCat = new HouseCat("Keyboard Cat");
   // <insert assertion method here>
}
  1. Assert.AreEqual(13, keyboardCat.Weight);
  2. Assert.IsNotNull(keyboardCat.Weight);
  3. Assert.AreEqual(13, keyboardCat.Weight, .001);
  4. Assert.IsNotNull(keyboardCat.weight);
Question

What additional assert method can we add to this test to properly verify that HouseCat inherits Eat()?

1
2
3
4
5
6
7
8
[TestMethod]
public void IsNotInitiallyTired()
{
   HouseCat keyboardCat = new HouseCat("Keyboard Cat");
   Assert.IsFalse(keyboardCat.Hungry);
   Assert.IsFalse(keyboardCat.Tired);
   keyboardCat.Eat();
}
  1. Assert.IsFalse(keyboardCat.Tired);
  2. Assert.IsTrue(keyboardCat.Tired);
  3. Assert.IsTrue(keyboardCat.Hungry);
  4. Assert.IsFalse(keyboardCat.tired);