1

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?

Community
  • 1
  • 1
sparks
  • 736
  • 1
  • 9
  • 29
  • the classics are mocking how it looks, maybe it has glasses, or freckles or something, you could mock that. Really it's a lot of improvisation. (joke). Also, I think this is a duplicate of [this](http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes) – Assaf Sep 05 '14 at 06:37
  • I don't feel like this is a duplicate since it seems like the answer to the other question is reflection, which I already have tried. Reflection would work if it weren't for the byte code error. Granted this is theoretically a temporary issue until PowerMock / EasyMock release a patch for this error. – sparks Sep 05 '14 at 15:10

2 Answers2

0

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.

troig
  • 7,072
  • 4
  • 37
  • 63
0

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.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92