Java 如何验证父类的super.method()的调用?
我有三门非常简单的课。其中一个扩展了父类Java 如何验证父类的super.method()的调用?,java,unit-testing,mockito,powermock,Java,Unit Testing,Mockito,Powermock,我有三门非常简单的课。其中一个扩展了父类 public class Parent{ protected String print() { // some code } } 这是一个儿童班 public class Child extends Parent { /** * Shouldn't invoke protected Parent.print() of parent class. */ @Override pro
public class Parent{
protected String print() {
// some code
}
}
这是一个儿童班
public class Child extends Parent {
/**
* Shouldn't invoke protected Parent.print() of parent class.
*/
@Override
protected String print() {
// some additional behavior
return super.print();
}
}
和测试课
public class ChildTest {
@Test
public void should_mock_invocation_of_protected_method_of_parent_class() throws Exception {
// Given
Child child = PowerMockito.mock(Child.class);
Method method = PowerMockito.method(Parent.class, "print");
PowerMockito.when(child, method).withNoArguments().thenReturn("abc");
// When
String retrieved = child.print();
// Than
Mockito.verify(child, times(1)).print(); // verification of child method
Assert.assertEquals(retrieved, "abc");
}
}
我需要验证
super.print()
调用。我该怎么做?如果在子类“print()
方法中调用super.print()
,当然会调用print()
的父类实现。如何验证它是否确实发生取决于父类实现的实际操作
另外,代码
中的注释不应调用受保护的父类和父类的print()和父类的print()方法。
是错误的。这是一个很久以前的问题,但我是如何使用Mockito spy创建一个方法来调用子类中的父方法的:
public class Child extends Parent {
/**
* Shouldn't invoke protected Parent.print() of parent class.
*/
@Override
protected String print() {
// some additional behavior
return callParent();
}
protected callParent()
{
super.print();
}
}
在测试中:
@Test
public void sould_mock_invocation_of_protected_method_of_parent_class() throws Exception {
// Given
Child child = Mockito.spy(new Child());
Mockito.doReturn(null)
.when(child)
.callParent();
// When
String retrieved = child.print();
// Then
Mockito.verify(child, times(1)).callParent(); // verification of child method
Assert.assertEquals(retrieved, "abc");
}
注意:这个测试只检查我们在子类中调用父方法,这可以通过应用“组合重于继承”模式来解决
现在,您可以模拟和验证准父#doSomeMethod()调用。我需要验证是否调用了方法Parent.print()
。但同时我想模拟它(我不想调用realParent.method()
)。@Aaron然后在该方法中打印一些东西,并验证它是否被打印出来。@Aaron也许我不明白你想做什么。我不熟悉Mockito。实际上我想模拟父方法。但同时我想验证这个方法是否被调用。当然,我不需要执行父方法的逻辑(它调用“来模拟方法”)。这对我来说没有意义,如果您需要验证super.print()调用,它是通过验证子方法.print()调用来验证的。它调用超类print()以返回结果。或者,只测试父级。无论是否在子级中调用super.print()
,测试都会通过。Mockito似乎无法处理这种情况:请看,您的答案可能对某些人有用,但它没有解决OP明确要求的super
public class QuasiChild {
private final QuasiParent quasiParent;
public QuasiChild(QuasiParent quasiParent) {
this.quasiParent = quasiParent;
}
public void someMethod() {
// do something...
quasiParent.someMethod();
}
}