Skip to content

Mock static methods in Junit 5 in Java and Spock framework

  • rob 
  • Blog

Problem –

Mocking static methods are sometimes tricky in many unit test frameworks. Generally developers do not rely on static methods while using frameworks like Spring but sometimes creation of static methods are beneficial. Static methods have benefits like memory efficiency, global access, object independence and performance.

Till Junit 4, we have PowerMockito in both Java Junit and Groovy Spock frameworks. In Junit 5 and Mockito 3.4.0, it is removed and replaced with Mockito.mockStatic(Class<T> classToMock)

Junit mock static method, Spock framework static method

Before Junit 5 or Mockito 3.4.0

You need to use below power mock dependency.

Maven –


Gradle –

dependencies {
testImplementation 'org.powermock:powermock-api-mockito2:2.0.9'

In both Java Junit and Groovy Spock framework you can use PowerMockito. Refer to below Spock example code.

class MockitoSpec extends Specification {
def "when getMySet is called then output should return"() {
given:Set mySet = new LinkedHashSet<>()

After Junit 5 or Mockito 3.4.0

You need to remove all PowerMockito related dependencies because starting version 3.4.0, Mockito supports mocking static methods directly. Use below dependency to support mockStatic(Class classToMock)

Maven –


Gradle –

dependencies {
testImplementation 'org.mockito:mockito-inline:4.6.1'

mockStatic() needs to be declared in try-with-resources. You need Java 8+ for Junit framework and Groovy 3 for Spock framework. You need to remove all three annotations @RunWith, @PowerMockRunnerDelegate and @PrepareForTest.

For Java Junit implementation use below code.

try (MockedStatic mocked = Mockito.mockStatic(StaticMethodClass.class)) {
mocked.when(() -> StaticMethodClass::getMySet()).thenReturn(mySet);

For Groovy Spock implementation use below code.

var mockedStatic = mockStatic(StaticMethodClass.class)
mockedStatic.when({ -> StaticMethodClass.getMySet() }).thenReturn(mySet)

As you see, Mockito provides a graceful solution using a narrower scope for mocked static objects via lambda. Join the developers group of fixmydev now for more technical analysis like this.

Leave a Reply

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