1

假设有一个超类

class SuperClass {
    SuperClass(Foo foo) {
        this.foo = foo;
    }

    SuperClass() {
        this.foo = new DefaultFoo();
    }
}

还有一个子类

class SubClass extends SuperClass {
     SubClass(Foo foo) {
        super(foo);
    }
}

被测试的类是SubClass. 我想验证SubClass'构造函数确实在调用它的超类的非空构造函数。有什么办法可以做到这一点?

4

4 回答 4

3

I would test this via the super constructors side effects. e.g. does it set particular fields or change behaviour ?

Note that the implementation of your class should really be shielded from the tests. So you're only interested in how it affects the constructed entity. Otherwise if/when you refactor your class hierarchy you'd have to change your tests, whereas you need them to remain the same in order to perform a regression.

于 2012-10-10T08:14:01.493 回答
1

为了从单元测试中检查,您可以简单地创建一个Foo实例,将其传递给SubClass构造函数,然后检查是否instance.getFoo()返回完全相同的引用。

于 2012-10-10T08:16:28.310 回答
1

通过模拟超类,使用 jmockit ( http://jmockit.googlecode.com )应该可以做到这一点。这是示例

(来自:https ://groups.google.com/forum/?fromgroups=#!topic/jmockit-users/O-w9VJm4xOc )

public class TestClassUnderTest { 

     public class ClassUnderTest extends BaseClassForClassUnderTest 
     { 
        public ClassUnderTest(ISomeInterface si) 
        { 
           super(si); 
         } 
         //... 
      } 
@Test 
public void testSuperConstructorCall() 
{ 
    final ISomeInterface si = new ISomeInterface() 
    { 
    }; 

    Mockit.setUpMock(BaseClassForClassUnderTest.class, new Object() { 
        @Mock 
        public void $init(ISomeInterface si_param) 
        { 
            assertNotNull(si_param); 
            assertTrue(si_param == si); 
        } 
    }); 

    ClassUnderTest cut = new ClassUnderTest(si); 
} 

}

于 2012-10-10T08:18:00.100 回答
0

您可以在超类中放置一个布尔字段,并在非空构造函数中将其设置为“真”,从而在调用非空构造函数时将其设置为“真”。检查相应对象的布尔实例字段的状态,以了解调用了哪个构造函数。

于 2012-10-10T08:27:29.850 回答