Mocking static methods in JUnit using PowerMock

25 / Jun / 2015 by Haider Ali 0 comments

We usually need to mock lots of functionality while writing unit tests. In JUnit we have many frameworks to achieve this, but PowerMock is very powerfull API to mock classes. For mocking static functions we have a bit different approach due to their different nature. Assuming we have two utility classes with static functions and one class for which we need to write unit test case.

FirstUtility class:

[java]

public class FirstUtil {

public static String staticFunction(String parameter){
return parameter;
}

}

[/java]

SecondUtility class:

[java]

public class SecondUtil {

public static String staticFunction(String parameter){
return parameter;
}

}

[/java]

Class for Unit Test:

[java]
public class ForTest {
public String executeFunction(){
FirstUtil.staticFunction("FirstUtil");
SecondUtil.staticFunction("SecondUtil");
return "success";
}
}

[/java]

For the above code we need to mock two classes. So we need to include them in annotation “PrepareForTest”.

[java]

@PowerMockIgnore("org.apache.http.conn.ssl.*")
@RunWith(PowerMockRunner.class)
@PrepareForTest({FirstUtil.class,SecondUtil.class})

public class TestToMockStatic {

@Rule

@Test
public void testProductOrderProcessing() throws ClientProtocolException, IOException{
PowerMockito.mockStatic(FirstUtil.class);//For mocking static functions
PowerMockito.mockStatic(SecondUtil.class);

Mockito.when(FirstUtil.staticFunction(parameter)).thenReturn(mockedStaticFunction(parameter));
Mockito.when(SecondUtil.staticFunction(parameter)).thenReturn(mockedStaticFunction(parameter));

ForTest forTest= new ForTest();

assertEquals(forTest.executeFunction(),"success");

}

public void mockedStaticFunction(String parameter){
return parameter;
}

}
[/java]

 

Note : In above code you can see annotation @PowerMockIgnore . This is used to defer the loading of classes with the names supplied to value() to the system classloader.

Maven dependencies for mocking framework:

 

[xml]
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.6.2</version>
</dependency>

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-support</artifactId>
<version>1.6.2</version>
</dependency>

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
[/xml]

 

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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