7.6. 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? (wink)

Knowing what we know now about Unit Testing and Inheritance, we can test that our subclasses extend their base classes.

We can add a test folder to our inheritance package and write some code to ensure that HouseCat inherits what we expect it to.

1
2
3
4
5
@Test
public void inheritsSuperInFirstConstructor() {
   HouseCat keyboardCat = new HouseCat("Keyboard Cat", 7);
   assertEquals(7, keyboardCat.getWeight(), .001);
}

Here, we’re testing that one of our HouseCat constructors will call the Cat constructor and appropriately assign the HouseCat object’s weight property. 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 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.

7.6.1. Check Your Understanding

Question

Fill in the blank to test that the default constructor of Cat is called when the second constructor on HouseCat is used?

Second HouseCat constructor:

14
15
16
public HouseCat(String aName) {
  name = aName;
}
1
2
3
4
5
@Test
public void inheritsDefaultCatInSecondConstructor() {
   HouseCat keyboardCat = new HouseCat("Keyboard Cat");
   <insert assertion method here>
}
  1. assertEquals(13, keyboardCat.getWeight());

  2. assertNotNull(keyboardCat.getWeight());

  3. assertEquals(13, keyboardCat.getWeight(), .001);

  4. assertNotNull(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
@Test
public void isNotInitiallyTired() {
   HouseCat keyboardCat = new HouseCat("Keyboard Cat");
   assertFalse(keyboardCat.isHungry());
   assertFalse(keyboardCat.isTired());
   keyboardCat.eat();
}
  1. assertFalse(keyboardCat.isTired());

  2. assertTrue(keyboardCat.isTired());

  3. assertTrue(keyboardCat.isHungry());

  4. assertFalse(keyboardCat.tired);