我有一个实用程序类,它是最终类。在那里我使用注入(inject)来注入(inject) 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);
}
}
}
当我为此方法编写单元测试时,我必须模拟 LOGGER 否则它会抛出空指针异常。我如何在不创建此类的实例的情况下模拟此 LOGGER。我试图将变量白盒化。但它只适用于实例?
最佳答案
这段代码工作正常。要设置静态字段,您需要将一个类传递给 org.powermock.reflect.Whitebox.setInternalState
。请确保您使用包 org.powermock.reflect
中的 PowerMock 类,因为 Mockito 具有同名的类。
@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));
}
}
关于java - 使用 Powermock 模拟静态私有(private)最终变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36369634/