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

all*_*ode 7 java testing easymock mocking

比如说我有这个课程:

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

我想测试一下Foo.a.我想嘲笑Foo.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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Raj*_*uri 13

在EasyMock 3.0+中,您可以使用mockbuilder创建Partial mock

EasyMock.createMockBuilder(class).addMockedMethod("MethodName").createMock();
Run Code Online (Sandbox Code Playgroud)


rad*_*ish 3

我想您可以使用 EasyMock 扩展库来做到这一点。您可以在部分模拟中找到一个简单的示例

  • 从 EasyMock 3.1 开始,ClassExtensions 库已被弃用,部分模拟已移至 EasyMock 本身。这表明它可以与 JUnit 3 一起使用,所以你可能很幸运:http://easymock.org/EasyMock3_1_Documentation.html (3认同)