在代码库中,我具有以下结构:
abstract class Bar{
public Bar(){
....
}
....
public Bar(int x, int y){
}
....
}
Bar
然后由 Foo
扩展。
abstract class Foo extends Bar{
public Foo(){
super();
....
}
public Foo(int x){
super(x,0); // call parent's specific constructor
....
}
....
}
我尝试了以下 jUnit 测试用例,但无法编译:
class FooTest{
Foo _foo;
@Test
void testFooConstructor(){
new Expectations(){
Bar bar;
{
bar = new Bar(anyInt,0); // error, obviously Bar cannot be instantiated.
}
}
_foo = new Foo(anyInt){ // empty implementation
//Override any abstract methods
}
}
}
我写了上面的方法,因为我看到了this SO question ,但抽象类可能未启动,因此失败。
另外,我也尝试过:
class FooTest{
Foo _foo;
@Test
void testFooConstructor(){
_foo = new Foo(anyInt){ // empty implementation
//Override any abstract methods
}
new Expectations(){
Bar bar;
{
invoke(bar,"Bar",anyInt,0); //Invocations.invoke
}
}
invoke(_foo,"Foo",anyInt);
}
}
但是我的测试结果是:
java.lang.IllegalArgumentException: No compatible method found: Bar(int,int) at unit.src.com.test.FooTest$1.(line number)
怎样才能达到预期的效果?有没有办法实现这个测试?
最佳答案
子类必须始终调用 super 构造函数,无论是隐式的(这也意味着调用
super()
在你的构造函数中是多余的)或显式的(带有参数)。如果您想对此进行测试,请测试可观察的行为,即您可以测试的 super 构造函数的调用将执行哪些操作。
关于java - 验证父级的特定抽象构造函数是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14406797/