Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 815
allyourcode Avatar asked May 30 '12 22:05

allyourcode


People also ask

How do you mock on EasyMock?

EasyMock also supports injecting mocks using annotations. To use them, we need to run our unit tests with EasyMockRunner so that it processes @Mock and @TestSubject annotations. Equivalent to mock(…), a mock will be injected into fields annotated with @Mock.

Is EasyMock a mocking framework?

EasyMock is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. EasyMock is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.

Which API is used in creation of partial mocks with EasyMock?

Interface IMockBuilder<T> Helps the creation of partial mocks with EasyMock .


1 Answers

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

EasyMock.createMockBuilder(class).addMockedMethod("MethodName").createMock();
like image 155
Rajani Karuturi Avatar answered Oct 22 '22 22:10

Rajani Karuturi