17

Let's say I have a non-final concrete class with a final method like the one below.

public class ABC {
  public final String myMethod(){
      return "test test";
  }
}

is it possible to mock myMethod() to return something else when it is called in junit using Powermockito? Thank you

rekire
  • 47,260
  • 30
  • 167
  • 264
sura watthana
  • 291
  • 3
  • 4
  • 6

1 Answers1

32

This works :

@RunWith(PowerMockRunner.class)
@PrepareForTest(ABC.class)
public class ABCTest {

    @Test
    public void finalCouldBeMock() {
        final ABC abc = PowerMockito.mock(ABC.class);
        PowerMockito.when(abc.myMethod()).thenReturn("toto");
        assertEquals("toto", abc.myMethod());
    }
}
gontard
  • 28,720
  • 11
  • 94
  • 117
  • yes it is supposed to work but when I tried I always got exception below. I'm wondering if I have set something wrong? `java.lang.NoClassDefFoundError: org/mockito/internal/MockitoInvocationHandler at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138) at ABCTest.finalCouldBeMock(ABCTest.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source)` – sura watthana Aug 28 '12 at 03:36
  • @surawatthana You have to add Mockito in your classpath – gontard Aug 28 '12 at 07:39
  • Hi Gontard, How dO I add Mockito in my classpath in Eclipse? – sura watthana Aug 28 '12 at 09:26
  • If you are using maven, look [here](http://code.google.com/p/mockito/wiki/MavenUsers) else download [mockito.jar](http://mockito.googlecode.com/files/mockito-all-1.9.5-rc1.jar) then right click on your project -> Build path -> configure build path, librairies tab, add jar (select the downloaded library). – gontard Aug 28 '12 at 09:31
  • 8
    why do you guys always assume static imports are obvious? mentioning that you call PowerMockito.when(...) is quite helpful (even though given the question we can expect you are using PowerMockito) – Vince May 14 '14 at 15:29
  • 4
    Also, be sure you're statically importing `mock()` from `org.powermock.api.mockito.PowerMockito` and not from `org.mockito.Mockito`. My IDE automatically imported from the latter package, causing an error about not being able to mock final methods. – Oliver Hernandez Feb 24 '16 at 17:38