Is there a way to partially mock an object using EasyMock?

allyourcode picture allyourcode · May 31, 2012 · Viewed 19.2k times · Source

E.g. let's say I have this class:

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

And I want to test Foo.a. I want to mock Foo.b, because I'm testing that method separately. What I'm imagining is something like this:

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);
  }
}

I know I can write my own Foo subclass to do this sort of thing for me. But I don't want to do that if I don't have to, because it's tedious i.e. should be automated.

Answer

Rajani Karuturi picture Rajani Karuturi · Feb 5, 2013

In EasyMock 3.0+, you can create Partial mock using the mockbuilder

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