http://stackoverflow.com/questions/6645263/unit-testing-overridden-methods-which-call-super (This question has similar wording but is not the same)
I have something along the lines of:
public class SuperClass {
private int superClassInteger = 2;
public void superClassMethod() {
superClassInteger = 5;
}
public int getSuperClassInteger() {
return superClassInteger();
}
}
Then in my test I have:
public class SuperClassTest {
public void testSuperClassMethod() {
SuperClass superClass = new SuperClass();
superClass.superClassMethod();
assertEquals(5, super.getSuperClassInteger())
}
}
I then have a subclass:
public class SubClass {
private int subClassInteger = 2;
public void subClassMethod() {
super.superClassMethod();
subClassInteger = 32;
}
public int getSuperClassInteger() {
subClassInteger;
}
}
Then my test for the subclass:
public class SubClassTest {
public void testSubClassMethod() {
SubClass subClass = new SubClass();
subClass.subClassMethod();
assertEquals(5, subclass.getSuperClassInteger());
assertEquals(32, subclass.getSubClassInteger())
}
}
My problem is that to test the behavior of the subclass, I am repeating the test code I have for the super class. I could take out: assertEquals(5, subclass.getSuperClassInteger());
as I just want to test the business logic of the subclass. However, the problem with this is that if somebody accidentally removes the call to superClassMethod
the test will still pass. So I need verify that a call to super is made. What is a common way of testing this use case?
Note: I know composition / strategy pattern vs inheritance helps solve this problem but for that to be the solution you are basically saying that I should NEVER override a method and invoke super in my code (which I find hard to believe there will never be a use for)