peninha
peninha

Reputation: 191

How to mock a method call on the constructor using easymock?

I have a class that receives a factory as an argument that is called inside the constructor. It must be called there because the object should be fully initalized before it can be used. Something like:

class MyClass {

  private Foo foo;

  MyClass(FooFactory fooFactory, Bar bar) {
    this.foo = fooFactory.newFoo(bar);
  }
}

An instance of Foo cannot be directly passed to the constructor, so consider that this is a restriction of the problem. MyClass cannot be tested using EasyMock, because fooFactory would be a mock that was not initialized in the setUp:

private MyClass myClass;

  public void setUp() {
     FooFactory fooFactory = mock(fooFactory);
     Bar bar = new Bar();
     myClass = new MyClass(fooFactory, bar)
  }

So when setUp is called, the call for fooFactory.newFoo(bar) inside the constructor will fail with an IllegalStateException, because no such expectations were set.

The question is the, how can you mock method calls in the constructor?

Upvotes: 2

Views: 3665

Answers (1)

pingw33n
pingw33n

Reputation: 12510

You can EasyMock.reset(fooFactory) in setUp after MyClass is created.

Upvotes: 3

Related Questions