Search code examples
javaunit-testingguice

How to unit test a class which uses Google Guice?


I have a java class that looks like this:

@Inject
PerPixelImageUpdater(PixelUpdaterFactory pixelUpdaterFactory, @Assisted BufferedImage image){
    this.pixelUpdater = pixelUpdaterFactory.create(image);
}

public void someMethod(){
    // some stuff
    this.pixelUpdater.doSomething();
}

Google Guice is being used for dependency injection.

I am trying to write unit tests to cover someMethod() and I'm not sure the best way to instantiate the class under test.

My initial attempt was to use Guice to create the class:

ImageUpdaterFactory imageUpdaterFactory = injector.getInstance(ImageUpdaterFactory.class);
PerPixelImageUpdater perPixelImageUpdater = (PerPixelImageUpdater) imageUpdaterFactory.create(image);

But I'm not sure the best way to mock the call to this.pixelUpdater.doSomething() so I can test the other logic in the method under different scenarios.

Would it be better to use new to call the constructor and pass in a mocked factory? I'm struggling to find any documentation on the recommended best practice when unit testing classes using Guice.


Solution

  • Having just rewritten all my unit tests from using Guice-created objects to manually instantiated objects, I can say with certainty that manually creating them is much better for tests. It just gives so much more flexibility. Substituting either just one, or all of the arguments with mocks, fakes, test implementations, is a lot easier.

    I'm using the JUnit 5 dependency injection to make this a little easier for myself, having a "standard" extension that provides some of the more often used object graphs that Guice would normally create, and use it when needed. But when testing small parts of that graph, just manually create the objects.