How to mock static and final methods while writing JUnit?

Many people will point out that if you are mocking static or final method in your Junit that means something is not correct with the way source code is written and I totally concur with that. However sometimes you may end up in a situation where you have to mock static or final methods e.g. most of the vendor specific framework methods are declared as final.

The solution comes with PowerMock which is an extension to Mockito. PowerMock is the elixir for most of your advanced mocking/Junit needs. It comes with a cost of additional setting overhead though and can be intimidating at first. Please see the example below.

Problem Scenario:
Here is how the source code look:

public class MyClassA
{
public static long timeTaken(long starTime)
{
// want to mock this currentTime() method call.
return currentTime()+days;
}
public static long currentTime()
{
return System.currentTimeMillis();
}
}

Solution:
Lets say we are testing timeTaken() method and would like to mock currentTime()method then here is how you could do that using PowerMock

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClassA.class)
public class MyClassATest
{
@Test
public void timeTaken()
{
long whateveryouwant = 1L;
PowerMockito.spy(MyClassA.class);
PowerMockito.when(MyClassA.currentTime()).thenReturn(whateveryouwant);
long xxx = MyClassA.timeTaken(..);
assertEquals(...);
}

Here is what you need to have in your Pom if using Maven. (Please look the latest revision in http://repo2.maven.org/ )

    <dependency>
      <groupid>org.powermock</groupid>
      <artifactid>powermock-module-junit4</artifactid>
      <version>1.4.6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupid>org.powermock</groupid>
      <artifactid>powermock-api-mockito</artifactid>
      <version>1.4.6</version>
      <scope>test</scope>
    </dependency>

One thought on “How to mock static and final methods while writing JUnit?

Leave a Reply to Neil Buesing Cancel reply

Your email address will not be published. Required fields are marked *

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>