。如果C僅僅是您的層次結構中可擴展的最後一個類,而不是final
,您可以部分模擬C:
/**
* Tests C.foo(), which calls method bar() defined in A.
*/
@Test public void testFoo() {
// Spy on the system under test. This is unusal, but necessary here.
C c = Mockito.spy(new C());
// This ensures c.bar is never actually called, as opposed to Mockito.when().
Mockito.doReturn("quux").when(c).bar();
assertEquals("[quux]", c.foo());
}
如果C final
,不過,你可能不得不測試它作爲一個完整的單元,而不僅僅是它的升級過B.
@RunWith(JUnit4.class) public class CTest extends BTest {
@Override protected B createB() {
return new C();
}
@Test public void testCSpecificBehavior() { /* ... */ }
}
如果您在未來的選項,你可以考慮favoring composition over inheritance,因爲它爲您提供了更多的測試選項。