Easymock Instructions for use

Source: Internet
Author: User
Tags new features throw exception

Development Environment Version

Jdk 1.5

Junit 3.8

EasyMock 2.2

Eclipse 3.1.2

MyEclipse 4.1.0



Note: easymock2.0+ only supports jdk1.5+, because its code uses a lot of new features, such as for (:), method (...). and other usages. Easymock's initial version of 1.0 seemed to support simulation of the entity class, but it seems to have been removed from the very side of the version and quickly. Easymock Introduction






Easymock official page






EasyMock provides Mock Objects for interfaces in JUnit tests by generating them on the fly using Java ' s proxy mechanism. Due to EasyMock's unique style of recording expectations, most refactorings would not affect the Mock Objects. So EasyMock are a perfect fit for test-driven development.






Easymock is a virtual Test aid package for JUnit that provides a simulation of the interface class that can be used to complete a general test process by recording, replaying, and inspecting three steps, validating the invocation type, number of times, order of the method, and allowing the mock object to return a specified value or throw a specified exception. Download and install






Easymock is an open source project on the SourceForge, which can be downloaded freely, downloaded from there to the corresponding version of the compressed package can be extracted directly, for development, We just need to easymock.jar this file and add it to Eclipse's Project jar library to use.






In addition, since it is a package for testing in a junit environment, you need to add junit.jar when you actually use it . Concept Preparation






Before formal programming, there is a need to understand some of the concepts, some of which are the name of the class, but here is mainly to understand the concept he represents, to facilitate the further use of Easymock.




Method, Arguments, invocation

Expectedinvocation, actual

Mockcontrol, Mock

Reset (), Replay (), verify (), and so on.


method, Arguments,invocation



These three concepts have a dependency, method represents a way to simulate the class, arguments is the entry parameter of this method, invocation represents a call to a method of a simulation class, it contains a methods, Several argument (but the return value is not included here). In Easymock there is invocation this class, containing object[] arguments, method, Object mock arguments. expectedinvocation,actual






The former is representative of an expected method call, here is expected to refer to the addition of Matcher (s) invocation, not only to have the characteristics of invocation, but also add to its entry parameters of the Inspector (Matcher), The introduction of this concept is to ensure that similar arrays such as the comparison of such objects, or for the entry parameters to set a legal condition (not only simple equality, there is greater than equal, the string of Endwith, etc., the user as long as the rules, you can also make their own special Matcher). The classes associated with it are expectedinvocation, Expectedinvocationandresult, Expectedinvocationandresults, and the following two classes add the specified return value, which is appropriate for functions with return values.






The actual in the back is often used as a parameter in the Easymock source code to represent an actual method call in the replay process, and invocation belongs to a concept. Mockcontrol, Mock






Mockcontrol is the control class that is responsible for building the resources required for the entire framework, whose members behavior and recordstate state hold the sequence of method calls, and one control can manage multiple mocks at the same time. The mock object corresponds to a test class you need to test, it will automatically establish JAVAPROXYFACTORY<TOMOCK>, and then set up a proxy by javaproxyfactory; Objectmethodfilter (He holds a Mockinvocationhandler object, to Hashcode (), Equals (), toString () Three methods to judge) and Mockinvocationhandler (he holds a control object, which appears to be used to add invocation sequences). Reset (), Replay (), verify ()






The Reset () method resets the control object, and its internal reality is done by creating a new behavior and state two objects. Replay () is the end of the recording process, and he calls the Recordstate.closemethod () method to do most of the work. Verify () is used to check for expected and actual results after two steps of recording and playback are completed. Test structure model interface class: BaseInterface




public interface baseinterface{

 public void Methodabc ();

 Public somevalue methodabc (someargument someargument);


entity classes: Implementsbaseinterface, Targetclass

Implementsbaseinterface inherits the BaseInterface interface, providing a concrete implementation of the method.

public class targetclass{

 Private BaseInterface  member;

 ...//other Members

 public void Sommethods () {

    ......

    MEMBER.METHODABC ();

    MEMBER.METHODABC (somearguments, ...);

 }

 public void Setmemeber (BaseInterface  member) {

     This.memeber = member;

 }

 ...//Other methods

}

relationships between classes and methods



and Targetclass may have some internal members, such as now we happen to have a baseinterface type of internal member member, and Targetclass happens to have Somemethods () Calls to METHODABC () and METHODABC (Someargument someargument) in BaseInterface are required. Test class: Targetclasstest






Targetclasstest is a JUnit test case class for testing the Targetclass class, which is our goal.




Import static org.easymock.easymock.*;

Import  ...

public class targetclasstest{

  Private Targetclass target;

  Private BaseInterface  mock;

  Private Imockscontrol Ctrl;

  public void SetUp () {

      CTRL = Createstrictcontrol ();

      Mock = Ctrl.createmock (Implementsbaseinterface.class); Set up Easymock test class

      target = new Targetclass ();

      Target.setmember (mock);   Add the newly created mock to the target member

  }

  public void Testsomemethods () throws exception{

      ...//Prepare to create some objects that will be used

      Ctrl.reset ();  Initialization

      MOCK.METHODABC ();

      Expect (MOCK.METHODABC (somearguments, ...)). Andreturn (somevalue); Since this method has a return value, it needs to be specified with the Andreturn () method, otherwise the test throws an exception

      Ctrl.replay ();  End the recorder process for the entire control, and enter playback below

      Target.somemethods ();

      Ctrl.verify ();  End playback, check, mainly check the playback process and recording process is consistent, for the mock object's method call type, quantity, order compliance requirements to verify. An exception is thrown if an error occurs, but there is no automatic check of the return value.

  }

}


for a description of the model Control



When there is only one mock object, we can also invoke the Createmock (class Clazz) method in the Easymock class without manually generating the control object, so that the corresponding reset (), Replay (), verify () Methods cannot use control, but use the Reset (mock), Replay (mock), verify (mock) methods in the Easymock class to manipulate only a single mock object, when there are multiple mock objects Asynchronous operations can be done (but that doesn't seem to make much sense). But in fact, the control object is bound to be generated, whether you build it manually or not.






The benefit of building a control object is that you can perform the reset (), Replay (), and verify () operations together when there are multiple mocks. Andreturn ()






This method is only used to manually set the return value of this method to the test class that is called when the method of the mock object needs to have a return value. In this example methodabc (arguments,......) Method requires the Andreturn () method to specify the return value to Targetclass when recorder. If you do not specify a return value for a method that has a return value, the test will throw "java.lang.IllegalStateException:missing behavior definition for the" preceeding method Call XXX "exception. Types of mocks






Easymock offers three types of mocks: Strictmock, Nicemock, mock.




Kinds Generating functions Check Order Checks whether the method invokes Call to a method that is not described

Mock Createmock () Whether Is Throw exception

Nicemock Createnicemock () Whether Is Returns 0, NULL, no exception thrown

Strictmock Createstrictmock () Is Is Throw exception

A little supplement

There are some methods that can be used to set the number of calls, such as times (), to set the number of occurrences of a call, and to use a method similar to Andreturn (value) for the recorder period method call.


Expect (* * *). times (3); Specifies that the method call appears three times

Equivalent


Expect (* * *);

Expect (* * *);

Expect (* * *);

You can also set it to appear without capping, or within a range of these methods can be found in the Mockscontrol class


times (int);

Times (min, max);  Set Max to integer maximum is not capped, in fact, set a bigger point is enough

Anytimes ();

Once ();

The internal principle of Easymock



Looked at a day and a half of the time, the principle of his some understanding, but not comprehensive, some deep understanding of the principle is not very clear, the first simple talk about the current understanding, it is likely to have a lot of errors in the place, if later found, will be modified in succession.







Easymock uses a thread to capture a mock object function call, so he has a special Lastcontrol class with three members to associate a thread with three different classes, Matcher is a match, argument is the entry parameter, Control contains most of the main content.




= new Weakhashmap<thread, mockscontrol> ();


Private static final Weakhashmap<thread, stack<object[]>> threadtocurrentarguments

= new Weakhashmap<thread, stack<object[]>> ();


Private static final Weakhashmap<thread, stack<iargumentmatcher>> Threadtoargumentmatcherstack

= new Weakhashmap<thread, stack<iargumentmatcher>> ();


Puzzle: Matcher and argument should all be associated with the specified invocation, but there is only control, and a control can have multiple mocks, a mock can have multiple method processes, how to determine Matcher, The correspondence between argument and method. is implemented through threading.





He recorder the method and its parameters, times, to the linear table, while the corresponding method, parameter, and times of the replay are recorded and compared to achieve the verify () function.







Invocation corresponds to a specific method call procedure, which may contain a return value of result.







The corresponding Expectedinvocation series class joins the Matcher and result, which is the expected functionality.







Unorderedbehavior is the lowest level behavior class, which mainly has addexpected () and Addactual () two methods, should be able to complete the desired save and test two functions. He has a expectedinvocationandresults list that can record some of the columns of the method expected, you can specify that a mock should be logged, but this is not confirmed.







Recorder and replay are mainly by Imockscontrolstate interface implementation class: Recorderstate and Replaystate, their respective roles.







The members of Recorderstate are: Expectedinvocation lastinvocation, Result lastResult, imocksbehavior behavior Behavior is used to record all incoming expectedinvocation, and those two lastxxx should be used to keep the last record. The verify () method throws an exception directly: Calling verify is not allowed in record state

Replaystate has only one imocksbehavior behavior member, and only Invoke () and verify () will not throw an exception directly. Should be specifically designed to handle the validation of the replay period as its name



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.