Easymock use method and principle

Source: Internet
Author: User

The mock method is a common technique in unit testing, and its main function is to simulate some objects that are not easy to construct or complex in the application, thus isolating the test from objects outside the bounds of the test.

Writing custom Mock objects requires additional coding effort and may introduce errors. EasyMock provides a way to dynamically build mock objects based on a specified interface, avoiding the hand-writing of mock objects. This article will show you how to use EasyMock for unit testing and analyze the principles of EasyMock. 1. Mock objects and EasyMock introduction Unit Test and mock method

Unit testing is the validation of the functionality of one module in an application. In unit testing, the problem that we often encounter is that the other co-modules in the application are not yet developed, or that the tested modules need to interact with objects that are not easily constructed and more complex. In addition, because the correctness of other modules is not certain, we cannot determine which module caused the problem found in the test.

Mock objects can simulate the behavior of other collaborative modules, and the test module can obtain an isolated test environment by collaborating with mock objects. In addition, mock objects can be used to simulate a test that is not easy to construct in your application (such as HttpServletRequest must be constructed in a Servlet container) and more complex objects, such as ResultSet objects in JDBC, to make your tests run smoothly. EasyMock Introduction

Manually constructing mock objects gives developers additional coding, and the code written to create mock objects is likely to introduce errors. Currently, there are many open source projects that support the dynamic building of Mock objects that can be dynamically generated based on existing interfaces or classes, which not only avoids the extra coding effort, but also reduces the likelihood of introducing errors.

EasyMock is a class library for generating Mock objects for a given interface in a simple way. It provides a simulation of the interface, the ability to record, replay, check three steps to complete the general testing process, you can verify the method call type, number, order, you can make the Mock object return the specified value or throw a specified exception. By EasyMock, we can construct Mock objects conveniently so that the unit test is carried out smoothly. Installing EasyMock

EasyMock is an open source project using the MIT license, which you can download to the relevant zip file in Sourceforge. Currently, the latest version of EasyMock you can download is 2.3 and it needs to be run on the Java 5.0 platform. If your app is running on a Java 1.3 or 1.4 platform, you can choose EasyMock1.2. After extracting the ZIP package, you can find Easymock.jar this file. If you use Eclipse as the IDE, add the Easymock.jar to the project's Libraries and you can use it (as shown in the following figure). In addition, because our test cases run in the JUNIT environment, you also need Junit.jar (version 3.8.1 or more). Figure 1:eclipse Libraries in the project

Back to top 2. Unit Testing with EasyMock

With EasyMock, we can create mock objects dynamically for the specified interface, and use mock objects to emulate a collaborative module or domain object, allowing the unit test to proceed smoothly. This process can be broadly divided into the following steps: Using EasyMock to generate mock objects, setting the expected behavior and output of mock objects, switching mock objects to Replay state, invoking mock object methods for unit testing, and verifying the behavior of mock objects Certificate

Next, we'll explain each of these steps. In addition to the basic steps above, EasyMock also provides support for features such as special Mock object types, specific parameter matching methods, and we will explain them in later chapters. using EasyMock to generate Mock objects

Depending on the interface or class specified, EasyMock is able to create mock objects dynamically (EasyMock only supports generating mock objects for the interface by default, and if a mock object needs to be generated for the class, an expansion pack can be implemented on the home page of EasyMock), we ResultSet Interface as an example to illustrate the function of Easymock. Java.sql.ResultSet is a familiar interface for every Java developer: the manifest 1:resultset interface

Public interface Java.sql.ResultSet {
...
Public abstract java.lang.String getString (int arg0) throws java.sql.SQLException;
public abstract double getdouble (int arg0) throws java.sql.SQLException;
......
}

In general, building a real RecordSet object requires a complex process: during development, developers typically write a dbutility class to get the database connection Connection and create a Statement with Connection. Executes a Statement can get to one or more ResultSet objects. Such a construction process is complex and relies on the correct operation of the database. Problems with databases or database interaction modules can affect the results of unit tests.

We can solve this problem by using EasyMock to dynamically build Mock objects of the ResultSet interface. Some simple test cases require only one mock object, at which point we can create mock objects in the following ways:

ResultSet Mockresultset = Createmock (Resultset.class);

Where Createmock is the static method provided by the Org.easymock.EasyMock class, you can introduce it via the static import (note: Static import is a new feature provided by Java 5.0).

If you need to use multiple mock objects in a relatively complex test case, EasyMock provides another mechanism for building and managing mock objects:

Imockscontrol control = Easymock.createcontrol ();
Java.sql.Connection mockconnection = Control.createmock (connection.class);
Java.sql.Statement mockstatement = Control.createmock (statement.class);
Java.sql.ResultSet Mockresultset = Control.createmock (Resultset.class);

The CreateControl method of the EasyMock class creates an object Imockscontrol an interface that can create and manage multiple Mock objects. If you need to use multiple mock objects in your tests, we recommend that you use this mechanism because it provides a relatively convenient way to manage multiple mock objects.

If you are simulating a specific class rather than an interface, you need to download the extension pack EasyMock class Extension 2.2.2. When simulating a specific class, you simply replace the static method in the Org.easymock.EasyMock class with a static method in the Org.easymock.classextension.EasyMock class. set the expected behavior and output of a Mock object

During a complete test, a Mock object undergoes two states: the Record state and the Replay state. Once a Mock object is created, its state is set to Record. In the record state, the user can set the expected behavior and output of the mock object, which is recorded and saved in the mock object.

The process of adding mock object behavior can usually be divided into the following 3 steps: Making a call to a specific method of a mock object, and obtaining the corresponding iexpectation of the last method call through the static method provided by Org.easymock.EasyMock Expectlastcall Setters instance; Sets the expected output of the Mock object through the Iexpectationsetters instance.

Set expected return value

The behavior of a mock object can be simply understood as the invocation of the Mock object method and the output produced by the method invocation. In EasyMock 2.3, the addition and setting of Mock object behavior is accomplished through interface iexpectationsetters. The invocation of a Mock object method may produce two types of output: (1) A return value is generated, and (2) an exception is thrown. The interface Iexpectationsetters provides a variety of methods for setting the expected output, where the Andreturn method corresponds to the Set return value:

Iexpectationsetters<t> Andreturn (T value);

We still use the Mock object of the ResultSet interface as an example, if you want the return value of method mockresult.getstring (1) to be "My return value", then you can use the following statement:

Mockresultset.getstring (1);
Expectlastcall (). Andreturn ("My return value");

The above statement indicates that the Mockresultset getString method is called once, and the return value of this call is "My return". Sometimes we want the call of a method to always return an identical value, in order to avoid setting the behavior of the Mock object once per call, we can use a method that sets the default return value:

void Andstubreturn (Object value);

Suppose we create Mock objects Mockstatement and Mockresultset for the Statement and ResultSet interfaces, and during testing we want the Mockstatement method of the ExecuteQuery object to always return Mockresultset, we can use the following statement

Mockstatement.executequery ("SELECT * from sales_order_table");
Expectlastcall (). Andstubreturn (Mockresultset);

EasyMock the Object.Equals () method is used by default when matching parameter values. Therefore, if we use "SELECT * from Sales_order_table" as the parameter, the expected method will not be called. If you want the SQL statements in the example above to be case-insensitive, you can solve this problem with a special parameter match, which we'll explain in the chapter "using parameter Matching in EasyMock".

Set expected exception throws

The expected output of an object's behavior is likely to throw an exception, in addition to the return value. Iexpectationsetters provides a way to set the expected throw exception:

Iexpectationsetters<t> Andthrow (Throwable throwable);

Similar to setting the default return value, the Iexpectationsetters interface also provides a function to set the default exception to be thrown:

void Andstubthrow (Throwable throwable);

Set the number of expected method calls

With these functions, you can set the expected output of a Mock object's specific behavior. In addition to setting the expected output, the Iexpectationsetters interface allows the user to limit the number of calls to the method. Among the methods provided by Iexpectationsetters, one of the most common is the Times method:

Iexpectationsetters<t>times (int count);

This method can be used to set the number of calls of the Mock object method. Suppose we want Mockresultset's GetString method to be called 3 times during the test, and the return value of the period is "My return", we can use the following statement:

Mockresultset.getstring (1);
Expectlastcall (). Andreturn ("My return value"). Times (3);


Note that the return value of the Andreturn and Andthrow methods is still a iexpectationsetters instance, so we can continue to invoke the Times method on this basis.

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.