Use EasyMock extension to provide Mock objects for Class
Author: kongxx
Generally, when testing some classes, I need to rely on other classes or interfaces. At this time, these classes or interfaces may be just method signatures without real implementation. In this case, we can use some third-party class libraries to solve this problem, such as EasyMock and JMock. However, by default, both class libraries can only use Mock interfaces instead of Mock classes. How can we solve this problem? In fact, the EasyMock and JMock frameworks also provide a Mock solution for classes, but this function requires an extension class library they provide to implement. We can download these two extensions on their official website. For EasyMock download EasyMock Class Extension 2.0 _ Pre-Release, for JMock download jMock/CGLIB extension binary JAR.
Below is a small example:
Worker. java is a service class to be tested. It depends on an abstract Configuration object.
Class package easymock; Public class Worker { Private Configuration configuration; Public Configuration getConfiguration (){ Return configuration; } Public void setConfiguration (Configuration configuration ){ This. configuration = configuration; } Public boolean execute (){ String name = configuration. getName (); String type = configuration. getType (); If (name. equals ("System") & type. equals ("Snapshot ")){ // TODO Return true; } Return false; } } { Public static void main (String [] args) { System. out. println ("Hello World! "); } } |
Configuration. java is an abstract class that has some subclasses to implement its abstract methods.
Package easymock; Import java. io. File; Public abstract class Configuration { Protected String name; Protected String type; Public abstract Configuration initialize ate (File file ); Public abstract String getName (); Public abstract String getType (); } |
WorkerTest. java is a test class and requires Configuration object instances. Here, Mock has a Configuration object to support the execute method.
Package easymock; Import junit. framework. TestCase; Import org. easymock. classextension .*; Public class WorkerTest extends TestCase { Private Worker worker; Protected void setUp () throws Exception { Super. setUp (); Worker = new Worker (); } Protected void tearDown () throws Exception { Super. tearDown (); } /* * Test method for 'easymock.Worker.exe cute ()' */ Public void testExecute (){ Configuration conf = (Configuration) EasyMock. createMock (Configuration. class ); EasyMock. Except CT (conf. getName (). andReturn ("System "); EasyMock. Exact CT (conf. getType (). andReturn ("Snapshot "); EasyMock. replay (conf ); Worker. setConfiguration (conf ); // Method for executing the test AssertTrue(worker.exe cute ()); } } |
Run the JUnit test GreenBar. OK!