简体   繁体   English

PowerMockito:如何模拟最终的静态变量初始化

[英]PowerMockito: How to mock final static variable initialization

I'm writing test cases for Legacy code. 我正在为遗留代码编写测试用例。 I have a scenario like this. 我有这样的情况。

class A
{
  static final X = getUI().getResourceX();

  A(){}

  ....some methods to test....

}

I have to create spy object from class A . 我必须从A类创建间谍对象。 But while creating object it calls getUI method which returns null and it caused a NullpointerException. 但是在创建对象时,它将调用getUI方法,该方法返回null并导致NullpointerException。 So, how I eliminate getting null from getUI method? 那么,如何消除从getUI方法获取空值?

First I would advise to have a look here: How to mock a static final variable using JUnit, EasyMock or PowerMock 首先,我建议在这里看看: 如何使用JUnit,EasyMock或PowerMock模拟静态最终变量

In general, to fix your issue you can go with this: 通常,要解决您的问题,您可以这样做:

     Mockito.when(getUI().getResourceX()).thenReturn(whatYouNeed);

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

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