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

eg. 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 make fun Foo.b, because I am testing this method separately. What I present looks 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 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 that I can write my own subclass Footo do this for me. But I do not want to do this if I do not need it, because it is tiring, that is, to automate.

+5
source share
4 answers

I think you can do this using the EasyMock extension library. You can find a simple example here in Partial Mocking

+2
source

EasyMock 3.0+ Partial mock mockbuilder

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

OP (?), , - , . , .

, :

  Foo dummyFoo = new Foo() {
      @Override public Bar b() { return new Bar(); }
   };

, OP, ( // ..), EasyMock.

+2

JUnit 4 classextensions. ( , Mockito EasyMock, .) , :

public class FooTest extends TestCase {
    public static class FooSpy extends Foo {
        private final Fooable mockFoo;

        FooSpy(Fooable mockFoo) {
            this.mockFoo = mockFoo;
        }

        public Bar b() {
            return mockFoo.b();
        }
    }

    public void testA() {
        Fooable mockFoo = createMock(Foo.class);
        Fooable fooSpy = new FooSpy(mockFoo);

        // Foo 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(mockFoo.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(mockFoo);
        foo.a();
        verify(foo);
    }

}
+1

All Articles