简体   繁体   中英

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 .

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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