EasyMock extended to the use of Class provide Mock objects
EasyMock extended to the use of Class provide Mock objects
Author: kongxx
I usually Mody some kind of testing time to rely on some other type or interface, and this may be the only possible type or interface method signatures is not really realized. At this time we will be able to use some third-party libraries to solve this problem, for example, commonly used EasyMock, such as JMock. But these two libraries default under any circumstances, can only Mock interface, and not Mock category, then how should we solve this problem? In fact, two JMock EasyMock and also provides a framework for Mock of the solution, but this function need to provide them with an expanded class library can be achieved. We can they download on the official website of the two expansion. For EasyMock download EasyMock Class Extension 2.0_Pre-Release, JMock download jMock / CGLIB extension binary JAR.
Below is a small example:
Worker.java a need to test the business category, which 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 an abstract category, there will be a number of sub-categories to achieve its abstract way.
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 category, are required Configuration instance, here Mock Configuration object of a method used to execute provide support.
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);
/ / With the implementation of the test method
AssertTrue (worker.execute ());
)
)
Running JUnit tests GreenBar. OK!
Tags: Class, java class






