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

时间:2016-04-02 05:38:51

标签: java unit-testing mockito 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。我试着将变量whitebox。但它只适用于实例?

1 个答案:

答案 0 :(得分:5)

此代码工作正常。要设置静态字段,您需要将类传递给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));
    }
}