Roman Oxman
Roman Oxman

Reputation: 397

Java: Mock external library for testing

My tests are way too slow because I am using a configurations library in my code that takes at least 100ms any time I set or get something.

I am using Java and the configuration library that I use uses Apache ZooKeeper to store the data. I used Mockito and Powermock several times but never tried to mock an external library and I wondering if it is even possible.

import org.HybridConfiguration;

public class VisitManagerClass {

    private static final String COUNT_ENABLED = "countEnabled";
    private static final String COUNT = "count";

    public static void pageVisited() {
        boolean isCountEnabled = HybridConfiguration.getBooleanValue(COUNT_ENABLED);
        if (isCountEnabled) {
            long currentCount = HybridConfiguration.getLongValue(COUNT);
            HybridConfiguration.setValue(COUNT, Long.toString(currentCount + 1));
        }
    }
}

I would expect to be able to mock the library HybridConfiguration so that tests could run without any delay.

Upvotes: 2

Views: 1261

Answers (1)

k3b
k3b

Reputation: 14755

The way to go is create a service-facade that hides all api-calls to config-library/Apache-ZooKeeper behind an interface. your app only communicates with the interface and all methods calls to config-library/Apache-ZooKeeper are done in your service-implementation.

For testing you can easily mock out this service.

For more details see the-onion-architecture

Upvotes: 2

Related Questions