阅读更多
Mockup always comes to us when we try to break system dependency. The conventional mockup frameworks only allowed us to mock instance methods. So the static methods usually become to the death of testability.
Of course, we still have some way to make it become testable.
1. If the static methods invoke only happens in few classes, we could create an adaptor to isolate them. The implementation of adaptor is just simply delegation.
2. Unfortunately, sometimes your legacy system maybe full of static methods calling, they scatter in different tiers.
It indeed a bad smell, but before you refactor them, you may need to make them testable firstly. Now, jmockit comes to us.
"Tests can easily be written that will mock final classes, static methods, constructors, and so on. There are no limitations."
-- jmockit
The following example shows its ability to mock static methods.
//src file
public class ServiceFactory {
public static String getAService() {
return "real service";
}
}
//test file
import mockit.Mock;
import mockit.Mockit;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ServiceFactoryTest {
@Test
public void should_return_mock_service() {
Mockit.setUpMock(ServiceFactory.class, ServiceFactoryStub.class);
assertEquals("mock service", ServiceFactory.getAService());
}
private static class ServiceFactoryStub {
@Mock
public static String getAService() {
return "mock service";
}
}
}
Caution:
Make sure jmockit.jar appears before any JUnit jar file in the classpath. Otherwise, it will shows warning:
"WARNING: JMockit was initialized on demand, which may cause certain tests to fail;
please check the documentation for better ways to get it initialized."