Mockito 3 Mock Static Method

Creating static methods and classes increases the performance of the application. it creates a class at compile time hence saving run time creation.
previously Mockito didn't provide support for mocking static methods, and Power Mock was the only option, but with the release of 3.4.x version, Mockito provides MockedStatic API to support stubbing of the static method as well, it's a new feature so functionality is pretty much limited.

MockedStatic only creates mock for the current thread on which it's running hence it's not to use these methods from another thread. It is required to close these static mock objects using MockedStatic#close() otherwise static mock will remain active on the initiating thread. A better way is to create a static mock object using try-with-resources.

package com.example.mokito3.sujan;

public class AppleService {
    public static String saveApple() {
        String appleString = "i love apple";
        return appleString;
    }
}
package com.example.mokito3.sujan;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;

public class AppleServiceTest {
    @Test
    void saveAppleWithStaticMockTest() {
        try (MockedStatic<AppleService> mockedStatic = Mockito.mockStatic(AppleService.class)) {
            mockedStatic.when(AppleService::saveApple).thenReturn("i eat apple");
            Assertions.assertEquals("i eat apple", AppleService.saveApple());
        }
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories { jcenter() }
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'
    testImplementation('org.mockito:mockito-inline:3.4.0')
}
test {
    useJUnitPlatform()
}

 

follow us on