Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking static private final variable using Powermock?

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?

like image 277
Buru Avatar asked Dec 24 '22 07:12

Buru


1 Answers

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));
    }
}
like image 77
Arthur Zagretdinov Avatar answered Dec 28 '22 11:12

Arthur Zagretdinov