Java 使用Powermock模拟静态私有最终变量?
我有一个实用类,它是最后一个类。在那里,我使用了注入来注入记录器Java 使用Powermock模拟静态私有最终变量?,java,unit-testing,mockito,powermock,Java,Unit Testing,Mockito,Powermock,我有一个实用类,它是最后一个类。在那里,我使用了注入来注入记录器 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
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);
}
}
}
当我为这个方法编写单元测试时,我必须模拟记录器,否则它将抛出空指针异常。如何在不创建此类实例的情况下模拟此记录器。我试图对变量进行白盒处理。但它只适用于实例?此代码运行良好。要设置静态字段,需要将类传递给
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));
}
}
对您有用吗?默认情况下,guice不允许按设计进行静态注入。但我们可以要求,我不知道。我也没有用过,但是如果它能够注入静态字段,也许可以用它在单元测试中注入一个模拟记录器?嗯,最简单的解决方法是将变量包私有化,并将测试放在同一个包中,但肯定有更好的方法。它需要更新。白盒不再使用。@user447607“不再使用”是什么意思?该类仍然存在于PowerMock中,并将被保留。我没有计划将其移除。也许你的意思是有另一种方法可以做到这一点!对不起,我会澄清的。该类仍然存在,但它被认为是内部API的一部分,不建议使用它。@user447607我认为您混合了Mockito的
Whitebox
和PowerMock的Whitebox
。在PowerMock中,这个类是公共的。内部API是WhiteboxImpl
。确实如此。原则上我会给它取个别的名字。好的,当系统解锁时,我会修正我的投票。