繁体   English   中英

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

[英]Mocking static private final variable using Powermock?

我有一个实用程序类,它是最后一堂课。 在那里,我使用注入来注入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));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM