有没有办法使用EasyMock部分模拟对象?

2022-09-04 01:37:14

例如,假设我有这个类:

public class Foo Implements Fooable {
  public void a() {
    // does some stuff
    bar = b();
    // moar coadz
  }
  public Bar b() {
    // blah
  }
  // ...
}

我想测试.我想嘲笑,因为我正在单独测试该方法。我想象的是这样的:Foo.aFoo.b

public class FooTest extends TestCase {
  public void testA() {
    Fooable foo = createPartialMock(
      Fooable.class,  // like with createMock
      Foo  // class where non-mocked method implementations live
    );

    // Foo's implementation of b is not used.
    // Rather, it is replaced with a dummy implementation
    // that records calls that are supposed to be made;
    // and returns a hard coded value (i.e. new Bar()).
    expect(foo.b()).andReturn(new Bar());

    // The rest is the same as with createMock:
    //   1. Stop recording expected calls.
    //   2. Run code under test.
    //   3. Verify that recorded calls were made.
    replay(foo);
    foo.a();
    verify(foo);
  }
}

我知道我可以编写自己的子类来为我做这种事情。但是,如果没有必要,我不想这样做,因为它很乏味,即应该自动化。Foo


答案 1

在 EasyMock 3.0+ 中,您可以使用 mockbuilder 创建部分模拟

EasyMock.createMockBuilder(class).addMockedMethod("MethodName").createMock();

答案 2

我想你可以使用EasyMock扩展库来做到这一点。你可以在这个部分嘲笑中找到一个简单的例子