How to mock static method call by constructor?

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?

  • Answer:

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

peninha at Stack Overflow Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.