问题
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