Mocking static private final variable using Powermock?

爷,独闯天下 提交于 2020-01-24 09:44:05

问题


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?


回答1:


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));
    }
}


来源:https://stackoverflow.com/questions/36369634/mocking-static-private-final-variable-using-powermock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!