EasyMock documentation sucks!
Stages of using EasyMock:
- Creating mock objects
- Expectations setting and behaviour. As EasyMock documentations says: if you would like to use matchers in a call, you have to specify matchers for all arguments of the method call.
- Replay stage. This tells EasyMock that we no longer wish to record expected method calls.
- Actual method test call
- Assert your tests
- verify(). This includes validating that all methods that were expected to be called were called and that any calls that were not expected are also noted.
Classes involved in the example:
- BeingTested: The class that we are writing unit tests for
- UnitTestExample: The unit test class
- BeingMocked: The class that is being mocked
The portion of unit test in UnitTestExample would look like this:
BeingMocked mock = createMock(BeingMocked.class); // creating mock
BeingTested test = new BeingTested();
expect(mock.doSomethingElse(...)).andReturn(...); // expectation and behaviour
replay();
test.doSomething(mock);
assert(...);
verify(mock);
To expect methods that return void your need to use EasyMock.expectLastCall(). I just invoke the void method on the mock, and EasyMock captures the result. If I need to change some detail of the expectation, then I call EasyMock.expectLastCall() immediately after invoking the mock method.
To expect throwing an exception on a mock use: expect(someMock.method(anyObject())).andThrow(new SomeSortOfException());
This can get you started. Also read http://jeantessier.com/SoftwareEngineering/Mocking.html
Have a look at PowerMock as well.