4

I have a utility class which is a final class. There i have used injection for injecting LOGGER.

public final class Utilities {

    @Inject
    private static Logger.ALogger LOGGER;

    private Utilities() {
       //this is the default constructor. so there is no implementation
    }

    public static String convertToURl(string input){
       try{
             //do some job
          }catch(IllegalArgumentException ex){
             LOGGER.error("Invalid Format", ex);
          }
   }

}

While I writing unit testing for this method i have to mock LOGGER otherwise it will throw null pointer exception. How can i mock this LOGGER without creating instance of this class. I tried to whitebox the variable. But it only works with instances?

Bruce
  • 8,609
  • 8
  • 54
  • 83
  • Does [the injection to static field](http://stackoverflow.com/questions/19225179/is-it-possible-to-inject-a-cdi-bean-into-a-static-variable-in-java-ee-6) work for you? – fracz Apr 02 '16 at 05:47
  • by default guice doesn't allow static injection by design. But we can request [this](http://stackoverflow.com/questions/28513147/guice-injection-in-static-variable) – Bruce Apr 02 '16 at 05:56
  • I didn't know that. I haven't used that either, but if it's able to inject static field, maybe use it to inject a mock of logger in unit test? – fracz Apr 02 '16 at 06:05
  • Well, the easiest workaround is to make the variable package-private and put tests in the same package, but there's gotta be a better way. – Sergei Tachenov Apr 02 '16 at 06:55

1 Answers1

11

This code works fine. To set static field you need to pass a class to org.powermock.reflect.Whitebox.setInternalState. Please, ensure that you use PowerMock's class from the package org.powermock.reflect because Mockito has the class with the same name.

 @RunWith(PowerMockRunner.class)
 public class UtilitiesTest {

    @Mock
    private Logger.ALogger aLogger;

    @Before
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this); // for case them used another runner
        Whitebox.setInternalState(CcpProcessorUtilities.class, "LOGGER", aLogger);
    }

    @Test
    public void testLogger() throws Exception {
        Utilities.convertToURl("");
        verify(aLogger).error(eq("Invalid Format"), any(IllegalArgumentException.class));
    }
}
Artur Zagretdinov
  • 2,034
  • 13
  • 22