简体   繁体   中英

How to mock a private static final

With the new error popping up with java 7 & 8 when using Mockito and PowerMockRunner, Java will throw an Error in byte code exception when there is a static final variable involved. This is due to the now stricter byte code verification and mocking static final objects editing the byte code in order to successfully mock.

I have the following class that I am trying to mock:

public class ClassToBeMocked {
    private static final int LIMIT_FROM_PROPERTIES = AnotherClazz.methodToRetrieveFromMap("String being called")

    //more stuff
}

I have seen that you can get around this by by using reflection, seen here How to mock a static final variable using JUnit, EasyMock or PowerMock and here PowerMock: mock out private static final variable, a concrete example (not a great solution but it should work). However, using reflection requires that the object already be instantiated, and I am getting the bytecode exception when trying to instantiate ClassToBeMocked.

I have also tried mocking the AnotherClazz.methodToRetrieveFromMap(String) in the unit test (using correct syntax):

Mockito.when( AnotherClazz.methodToRetrieveFromMap("String being called") ).thenReturn(10);

However, This results in the byte code error again.

Is there a way around this catch-22 or a different framework or unit runner that would be better to use?

I think there is no way to do this without reflection. Anyway, I consider there is probably something 'wrong' in your design if you need to change static final constants, although you need it only for test scope.

As you say in your question, there are some ways to do it with PowerMock / EasyMock , but they still remain reflection anyway.

I'll be waiting for possible alternatives in other answers.

I would suggest you to consider changing of your production code to avid usage static and final. These are well known testability killers. Bytecode manipulation problems you are experiencing are known issues when you try to fake these constructs.

BTW, Make sure that your PowerMock version is up to date. Also make sure that your Mockito version match with PowerMock. You can find PowerMock version matrix here.

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