使用 Powermock 模拟静态私有最终变量?

Mocking static private final variable using Powermock?

我有一个实用程序 class,它是最终的 class。在那里我使用注入来注入 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 否则它会抛出空指针异常。我如何在不创建此 class 实例的情况下模拟此 LOGGER。我试图将变量白盒化。但它只适用于实例?

这段代码工作正常。要设置静态字段,您需要将 class 传递给 org.powermock.reflect.Whitebox.setInternalState。请确保您使用包 org.powermock.reflect 中的 PowerMock 的 class,因为 Mockito 具有同名的 class。

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