我可以模拟一个超类方法调用吗?
有时,您希望测试一个类方法,并且希望在调用超类方法时进行预期。我没有找到一种方法来使用easymock或jmock在java中做这个期望(我认为这是不可能的)。
Sometimes, you want to test a class method and you want to do an expectation on a call of a super class method. I did not found a way to do this expectation in java using easymock or jmock (and I think it is not possible).
有一个(相对)干净的解决方案,使用超类方法逻辑创建委托,然后设置它的期望,但我不知道为什么以及何时使用该解决方案?任何想法/示例?
There is a (relative) clean solution, to create a delegate with the super class method logic and then set expectations on it, but I don't know why and when use that solution ¿any ideas/examples?
谢谢
嗯,如果你愿意,你可以。我不知道您是否熟悉 JMockit ,请查看它。当前版本是0.999.17同时,我们来看看它......
Well, you can if you want to. I don't know if you are familiar with JMockit, go check it out. The current version is 0.999.17 In the mean time, let's take a look at it...
假设以下类层次结构:
public class Bar {
public void bar() {
System.out.println("Bar#bar()");
}
}
public class Foo extends Bar {
public void bar() {
super.bar();
System.out.println("Foo#bar()");
}
}
然后,在 FooTest.java 您可以验证您实际上是从 Foo $ c $打电话给 Bar c>。
Then, using JMockit in your FooTest.java you can validate that you're actually making a call to Bar from Foo.
@MockClass(realClass = Bar.class)
public static class MockBar {
private boolean barCalled = false;
@Mock
public void bar() {
this.barCalled = true;
System.out.println("mocked bar");
}
}
@Test
public void barShouldCallSuperBar() {
MockBar mockBar = new MockBar();
Mockit.setUpMock(Bar.class, mockBar);
Foo foo = new Foo();
foo.bar();
Assert.assertTrue(mockBar.barCalled);
Mockit.tearDownMocks();
}