0

Trying to mock a final class using Mockito and PowerMock I'm getting the error :

    java.lang.IllegalArgumentException: Cannot subclass final class class MyFinalClass
    at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:447)
    at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
    at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
    at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)

this happens inside a huge project, then to isolate from weird effects I've just extracted MyFinalClass class into a little test project and now I'm able to mock it.

Doing some research I also found that the problem is getting the class for passing it to PowerMock

    final MyFinalClass mock = PowerMockito.mock(MyFinalClass.class);

because doing it inside my huge project and obtaining modifiers it's shown as public and final :

    MyFinalClass.class.getModifiers() == 17

but doing it inside my little test project it is shown as public only :

    MyFinalClass.class.getModifiers() == 1

Because getModifiers() method is native I can't debug inside it and see what is happening.

Any clue what can be causing this class modifiers not to be changed by PowerMock and left as a final class ? or how can I discover why PowerMock not working as expected inside my huge project ?

Bit-Man
  • 516
  • 4
  • 17
  • 2
    @Steven That's why he's using Powermock. Powermock messes with your bytecode, so that you're not actually testing what you _think_ you're testing. It looks like this has included changing a `final` class to non-final. – Dawood ibn Kareem Sep 17 '14 at 22:18
  • Agreed and happy that it works this way **but** the problem is about why this doesn't happen inside my _huge project_ – Bit-Man Sep 18 '14 at 12:41

0 Answers0