Can I use jmock to replace the implementation returned by the factory?

I have a factory that returns an interface FormatService

:

public class FormatServiceFactory {
    public FormatService getService() {
        ...
    }
}

      

Is it possible to mock this factory so that it always returns a stub implementation FormatService

- FormatServiceStub

in our unit tests?

+1


source to share


2 answers


Depends. How is the factory obtained / used by the code under test?

If it is explicitly expressed in the methods you are testing, or if it is a static factory, then you cannot mock it.

If it is injected into the tested object, you can create and inject a mocked factory before executing the test.



Rejecting a factory should be easy enough with JMock. From your example code, it looks like a class, not an interface, so you will have to either use the cglib version of JMock, or MockObjectTestCase in the cglib package for JMock 1, or the ClassImposteriser for JMock 2.

Once mocked, you can force it to return its in-depth implementation (or even the FormatService layout) when you define expectations for the getService () method.

+1


source


Mockery of stupidity = new JUnit4Mockery () {{setImposteriser (ClassImposteriser.INSTANCE);}};

final FormatServiceFactory factory = mockery.mock (FormatServiceFactory.class);



context.checking (new Expectations () {{oneOf (factory) .getService (); will (returnValue (new FormatServiceMock ()));}});

0


source







All Articles