PowerMockito to test MongoClient Singleton

Viewed 639

I have lazy singleton MongoConnection class with a static method which returns MongoClient instance on MongoConnection.getClient():

 public class MongoConnection {

    private static MongoClient mongoclient;

    private MongoConnection() {

    }

    public static MongoClient getClient() {
        if (mongoclient == null) {
            // code to initialize MongoClient
        }
        return mongoclient;
    }
}

How do I use PowerMockito to mock MongoConnection singleton and test getClient method.

I don't have choice over singleton because there will be single instance of MongoClient across the application (as per MongoDB documentation).

Note: i don't want to connect to actual DB in test because it will be integration test rather than JUnit; I just want to make sure if MongoClient is initialized with expected parameters. How to do I achieve this with PockerMockito?

Thank you

1 Answers

The following example shows you how to use Mockito with PowerMockito to mock your MongoConnection.getMongoClient():

@RunWith(PowerMockRunner.class)
@PrepareForTest({MongoConnection.class})
public class ATest {

    @Test
    public void aTestWhichRequiresMockingMongoConnection() {
        MongoClient mongoClient = Mockito.mock(MongoClient.class);
        PowerMockito.mockStatic(MongoConnection.class);

        Mockito.when(MongoConnection.getClient()).thenReturn(mongoClient);

        // set up some expectations on the mocked MongoClient returned by MongoConnection    
        Mockito.when(mongoClient.getDatabase("aDatabaseName")).thenReturn(...);

        // ... etc
    }
} 

This class is verified for:

  • Mockito v2.7.19
  • PowerMock v1.7.0
  • JUnit v4.12

As an aside, this:

i don't have choice over singleton because there will be single instance of MongoClient across the application(as per MongoDB documentation).

... does not mandate you to make your MongoClient static. You could make getClient() a non static method and ensure that MongoConnection is a singleton i.e. that your application only has single instance of it. Dependency injection solutions (such as Spring, Guice) have built-in support for ensuring that a dependency can be configured as a singleton.

Related