using Easymock extensions to provide mock objects for class
author:kongxx
Usually I need to rely on other classes or interfaces while testing some classes, and at this point maybe these classes or interfaces are just method signatures without real implementations. At this point we can use a number of third-party libraries to solve this problem, such as the commonly used easymock,jmock and so on. But these two class libraries can only mock interfaces by default, not mock classes, so how do we solve the problem? In fact, the Easymock and Jmock two frameworks also provide a way to mock the class, but this feature requires an extended class library that they provide. 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.
Here is a small example:
Worker.java a business class that needs to be tested, it relies 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 an abstract class, there are 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 configurate (file file);
Public abstract String getName ();
Public abstract String GetType (); }
|
Workertest.java a test class that requires a configuration object instance that mocks a configuration object to provide support for 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.execute () ' */ public void Testexecute () { Configuration conf = (Configuration) easymock.createmock (Configuration.class); Easymock.expect (Conf.getname ()). Andreturn ("System"); Easymock.expect (Conf.gettype ()). Andreturn ("Snapshot");
Easymock.replay (conf);
Worker.setconfiguration (conf);
To perform a method with a test Asserttrue (Worker.execute ()); } }
|
Run JUnit tests, Greenbar. Ok.