EasyMock就是一个经常使用的Mock工具，我们可以借助其快速生成我们想要的mock object。

Maven

## Mocking

### The first Mock Object

1. 创建mock object
2. 设定我们希望的mock的行为(function及其返回结果)
3. 切换对象到replay状态

### Using annotations

mock会由runner初始化，可以不用添加setUp方法来初始化mock。

• type，用于指定mock的类型(nice, strict)。
• name，用于指定mock名字。
• fieldName，用于specifying the target field name where the mock should be injected.

### EasyMockSupport

EasyMockSupport可以帮助我们跟踪创建的所有mock，自动的注册，replay以及verfiy这些mocks，可以省去显示进行这些步骤。

## Behavior

### A second test

Through the second, we expect a call to the mock.documentAdded() on the mock Object with the title of the document as argument.

### ** Changing Behavior for the Same Method Call

It is also possible to specify a changing behavior for a method. The method times, andReturn, andThrow may be chained. As an example, we define voteForRemoval("Document") to

• return 42 for the first three calls,
• throw a RuntimeException for the next four calls,
• return -42 once.

### Altering EasyMock default behavior

EasyMock provides a property mechanisim allowing to alter its behavior. It mainly aims at allowing to use a legacy behavior on a new version. Currently supported properties are:

easymock.notThreadSafeByDefault
If true, a mock won’t be thread-safe by default. Possible values are “true” or “false”. Default is false

easymock.enableThreadSafetyCheckByDefault
If true, thread-safety check feature will be on by default. Possible values are “true” or “false”. Default is false

easymock.disableClassMocking
Do not allow class mocking (only allow interface mocking). Possible values are “true” or “false”. Default is false.
Properties can be set in two ways.

In an easymock.properties file set in the classpath default package
By calling EasyMock.setEasyMockProperty. Constants are available in the EasyMock class. Setting properties in the code obviously override any property set in easymock.properties

### ** Using Stub Behavior for Methods

Sometimes, we would like our Mock Object to respond to some method calls, but we do not want to check how often they are called, when they are called, or even if they are called at all. This stub behavoir may be defined by using the methods andStubReturn(Object value), andStubThrow(Throwable throwable), andStubAnswer(IAnswer<T> answer) and asStub(). The following code configures the MockObject to answer 42 to voteForRemoval("Document") once and -1 for all other arguments:

### ** Reusing a Mock Object

Mock Objects may be reset by reset(mock).

If needed, a mock can also be converted from one type to another by calling resetToNice(mock), resetToDefault(mock) or resetToStrict(mock).

## Verification

### A first verification

message会列出所有missing的expected calls。

### Working with Exceptions

For specifying exceptions (more exactly: Throwables) to be thrown, the object returned by expectLastCall() and expect(T value) provides the method andThrow(Throwable throwable). The method has to be called in record state after the call to the Mock Object for which it specifies the Throwable to be thrown.

Unchecked exceptions (that is, RuntimeException, Error and all their subclasses) can be thrown from every method. Checked exceptions can only be thrown from the methods that do actually throw them.

### Creating Return Values or Exceptions

An alternative to IAnswer are the andDelegateTo and andStubDelegateTo methods. They allow to delegate the call to a concrete implementation of the mocked interface that will then provide the answer. The pros are that the arguments found in EasyMock.getCurrentArguments() for IAnswer are now passed to the method of the concrete implementation.

### Relaxing Call Counts

To relax the expected call counts, there are additional methods that may be used instead of times(int count):

to expect between min and max calls,

to expect at least one call, and

to expected an unrestricted number of calls.

If no call count is specified, one call is expected. If we would like to state this explicitely, once() or times(1) may be used.

### Switching Order Checking On and Off

Sometimes, it is necessary to have a Mock Object that checks the order of only some calls. In record phase, you may switch order checking on by calling checkOrder(mock, true) and switch it off by calling checkOrder(mock, false).

There are two differences between a strict Mock Object and a normal Mock Object:

A strict Mock Object has order checking enabled after creation.
A strict Mock Object has order checking enabled after reset (see Reusing a Mock Object).

### ** Flexible Expectations with Argument Matchers

Matches if the actual value is equals the expected value. Available for all primitive types and for objects.

Matches any value. Available for all primitive types and for objects.

Matches if the actual value is equal to the given value allowing the given delta. Available for floatand double.

Matches if the actual value is equal to the given value according to Arrays.equals(). Available for primitive and object arrays.

Matches if the actual value is null. Available for objects.

Matches if the actual value is not null. Available for objects.

Matches if the actual value is the same as the given value. Available for objects.

Matches if the actual value is an instance of the given class, or if it is in instance of a class that extends or implements the given class. Null always return false. Available for objects.

Matches if the actual value is less/less or equal/greater or equal/greater than the given value. Available for all numeric primitive types and Comparable.

Matches if the actual value starts with/contains/ends with the given value. Available for Strings.

Matches if the actual value/a substring of the actual value matches the given regular expression. Available for Strings.

Matches if the matchers used in first and second both match. Available for all primitive types and for objects.

Matches if one of the matchers used in first and second match. Available for all primitive types and for objects.

Matches if the matcher used in value does not match.

Matches if the actual value is equals according to Comparable.compareTo(X o). Available for all numeric primitive types and Comparable.

Matches if comparator.compare(actual, value) operator 0 where the operator is <,<=,>,>= or ==. Available for objects.

Matches any value but captures it in the Capture parameter for later access. You can do and(someMatcher(...), capture(c)) to capture a parameter from a specific call to the method. You can also specify a CaptureType telling that a given Capture should keep the first, the last, all or no captured values.

### Defining your own Argument Matchers

Sometimes it is desirable to define own argument matchers. Let’s say that an argument matcher is needed that matches an exception if the given exception has the same type and an equal message. It should be used this way:

Two steps are necessary to achieve this:

1. The new argument matcher has to be defined,
2. and the static method eqException has to be declared.

To define the new argument matcher, we implement the interface org.easymock.IArgumentMatcher. This interface contains two methods: matches(Object actual) checks whether the actual argument matches the given argument, and appendTo(StringBuffer buffer) appends a string representation of the argument matcher to the given string buffer. The implementation is straightforward:

The method eqException must create the argument matcher with the given Throwable, report it to EasyMock via the static method reportMatcher(IArgumentMatcher matcher), and return a value so that it may be used inside the call (typically 0, null or false). A first attempt may look like:

However, this only works if the method logThrowable in the example usage accepts Throwables, and does not require something more specific like a RuntimeException. In the latter case, our code sample would not compile:

Java 5.0 to the rescue: Instead of defining eqException with a Throwable as parameter and return value, we use a generic type that extends Throwable:

Refer to EasyMock user guide.