简体   繁体   English

在模拟中初始化静态最终变量

[英]Initializing a static final variable in a mock

I want to initialize a static final variable of a class differently when it is mocked, and when it is not. 我想以不同的方式初始化类的静态最终变量,而没有模拟时。 Is there any way to do this? 有什么办法吗?

Something like : 就像是 :

public class Test {    
   private static final Integer a = getA();

   private static Integer getA() {
      if(mocked) {
         return x;
      } else {
         return y;
      }
}

I think it's a bad idea (because you shouldn't be checking if your instance is mocked I think that would defeat the purpose of mocking), but your current method looks almost correct. 我认为这是一个坏主意(因为您不应该检查实例是否被模拟,但我认为这会破坏模拟的目的),但是您当前的方法看起来几乎是正确的。 I assume you wanted to specify that getA() returns int . 我假设您想指定getA()返回int

private static int getA() {
}

Of course, your method itself seems pointless - in this case, you might use a Conditional Operator ? : 当然,您的方法本身似乎毫无意义-在这种情况下,您可以使用条件运算符? : ? : like ? :喜欢

private static final Integer a = mocked ? x : y;

This is why statics are bad for unit testing. 这就是为什么静电对单元测试不利的原因。 The best solution is to convert the static to an instance method, and then add some indirection so that your unit test can mock/implement/override that method. 最好的解决方案是将静态方法转换为实例方法,然后添加一些间接方法,以便您的单元测试可以模拟/实现/覆盖该方法。 The only other option is to use reflection to forcibly override the value in your unit test, which is obviously more fragile (and hostile to running many unit tests in the same process/classloader). 唯一的其他选择是使用反射强制覆盖单元测试中的值,这显然更脆弱(并且不利于在同一进程/类加载器中运行许多单元测试)。

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

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