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 –

<dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito2</artifactId>
      <version>2.0.9</version>
      <scope>test</scope>
</dependency>

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.

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate()
@PrepareForTest(StaticMethodClass.class)
class MockitoSpec extends Specification {
def "when getMySet is called then output should return"() {
given:Set mySet = new LinkedHashSet<>()
mySet.add(1)mySet.add(2)
PowerMockito.mockStatic(StaticMethodClass.class)
Mockito.when(StaticMethodClass.getMySet()).thenReturn(mySet)
}
}

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 –

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-inline</artifactId>
  <version>4.6.1</version>
  <scope>test</scope>
</dependency>

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)
mockedStatic.close()

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 *