Mocking static methods with Mockito [java]


The typical strategy for dodging static methods that you have no way of avoiding using, is by creating wrapped objects and using the wrapper objects instead.

The wrapper objects become facades to the real static classes, and you do not test those.

A wrapper object could be something like

public class Slf4jMdcWrapper {
    public static final Slf4jMdcWrapper SINGLETON = new Slf4jMdcWrapper();

    public String myApisToTheSaticMethodsInSlf4jMdcStaticUtilityClass() {
        return MDC.getWhateverIWant();

Finally, your class under test can use this singleton object by, for example, having a default constructor for real life use:

public class SomeClassUnderTest {
    final Slf4jMdcWrapper myMockableObject;

    /** constructor used by CDI or whatever real life use case */
    public myClassUnderTestContructor() {
        this.myMockableObject = Slf4jMdcWrapper.SINGLETON;

    /** constructor used in tests*/
    myClassUnderTestContructor(Slf4jMdcWrapper myMock) {
        this.myMockableObject = myMock;

And here you have a class that can easily be tested, because you do not directly use a class with static methods.

If you are using CDI and can make use of the @Inject annotation then it is even easier. Just make your Wrapper bean @ApplicationScoped, get that thing injected as a collaborator (you do not even need messy constructors for testing), and go on with the mocking.


I've written a factory to produce java.sql.Connection objects:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return DriverManager.getConnection(...);
        } catch (SQLException e) {
            throw new RuntimeException(e);

I'd like to validate the parameters passed to DriverManager.getConnection, but I don't know how to mock a static method. I'm using JUnit 4 and Mockito for my test cases. Is there a good way to mock/verify this specific use-case?

Mock a static method with parameter

You can mock static methods using PowerMockito. Here is a complete example.

public class YourTestCase {
   public void testMethodThatCallsStaticMethod() {
      // mock all the static methods in a class called "Static"
      // use Mockito to set up your expectation

      // execute your test
      String result = Helper.getName("abc");

      //assert the result
      Assert.assertEquals("foo", result);

      // to start verifying behavior
      // IMPORTANT:  Call the static method you want to verify

You should/could use the Singleton pattern.

Basically all the static methods call an internal private object that do the actual logic (called the instance).

If you do this, you can provide a protected static method setInstance. During your test, you create a mocked instance and set it to the static class.

This is doable, but it's not the most elegant solution, but static calls are not that elegant in the first place. I'm answering as there was no possible way to refactor out the entire codebase (like using Dependency Injection for example)

For example:

class GlobalData {
    //private object that does all the actual logic
    private static GlobalData instance = new GlobalData();

    //constructor is private so no one can call it
    private GlobalData() {


    //delegate the static call to the internal instance
    static boolean doSomething(...){ return instance._doSomething(); }

    //use underscore to keep similar name but avoid ambiguous call
    private boolean _doSomething(...){ ... }

    //same here
    static xxx A() { return instance._A(); }
    private xxx _A() {...}

    //this is not public, so must be called from the same package
    //since the constructor is private, no one will be able to create a GlobalData
    //except for mockito
    static void setInstance(GlobalData instance) {
        GlobalData.instance = instance;

And then in your test (which should be in the same package):

GlobalData instanceMocked = mock(GlobalData.class);
//we mock the methods with underscore, as they are the instance methods, and
//not the class methods

This requires only a minor refactor in the class you are looking at, without touching the rest of the project, while achieving what you want.