【发布时间】:2011-03-29 16:34:10
【问题描述】:
假设我们有一个接口,它有两个方法:
public interface MyInterface {
public SomeType first();
public SomeType second();
}
该接口由MyInterfaceImpl实现。在实现内部,first() 调用 second() 来检索一些结果。
我想构建一个单元测试,它会根据来自second() 的内容断言来自first() 的内容,类似于:
1 public class MyInterfaceTest {
2 private MyInterface impl = new MyInterfaceImpl();
4 @Test
5 public void testFirst() {
6 // modify behaviour of .second()
7 impl.first();
8 assertSomething(...);
10 // modify behaviour of .second()
11 impl.first();
12 assertSomethingElse(...);
13 }
14 }
有没有一种简单的方法可以在2 行上创建一个模拟,以便直接调用对选定方法(例如first())的所有调用(委托给MyInterfaceImpl)而其他一些方法(例如@987654331 @) 替换为模拟对应项?
对于静态方法,这实际上很容易通过 PowerMock 实现,但对于动态方法,我需要类似的东西。
解决方案基于
MyInterface mock = EasyMock.createMock(MyInterface.class);
MyInterface real = new MyInterfaceImpl();
EasyMock.expect(mock.first()).andReturn(real.first()).anyTimes();
EasyMock.expect(mock.second()).andReturn(_somethingCustom_).anyTimes();
还不够好,尤其是对于具有大量方法(大量样板)的接口。我需要转发行为,因为real 实际上取决于其他模拟。
我希望这样的事情由框架来处理,而不是由我自己的类来处理。这可以实现吗?
【问题讨论】:
标签: java unit-testing junit easymock powermock