The goal of unit testing is to test the code behaved as exactly expected and smallest piece of testable software as possible, the approach to do so is use mock technology that code becomes independent, lets thing goes to easy. EasyMock provides Mock Objects for interfaces by generating them on the fly using Java’s proxy mechanism. In generic, it could be enough to do uniting test with EasyMock, but, at least I have met, it’s I wanted to mock static, private methods and even constructor, I did the research on the main standard mock frameworks, such as EasyMock, jmock and so on, they both don’t support this, the mock to static and final method is not allowed because these methods are invisible to users, it is a strong indicator for a bad design, I recommend it’s a good time to refactor your code, let’s more testable and stable.
If you have to do so, JMockit can help you, JMockit allows developers to write unit and integration tests without the testability issues typically found with other mocking APIs. Tests can easily be written that will mock final classes, static methods, constructors, and so on. There are no limitations.
I have a simple example explain how to mock a static method. First of all, you need to download the Jmockit from http://code.google.com/p/jmockit/. and import JMockit jars to IDE, then lets start write code.
The following example shows how to mock static methods.
This is the source file to be tested immediately, it just have a simple method getServiceName
.
public class ServiceFactory { public static String getServiceName() { return "new service"; } }
This is the test code that test class ServiceFactory
, we used @Mock
to annotate the method to ask desired return.
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.getServiceName()); } private static class ServiceFactoryStub { @Mock public static String getServiceName() { return "mock service"; } } }