RSS Feed for This PostCurrent Article

Java: Open Source Mocking Framework

Here are some mocking frameworks that I have used

image

JMock is a library that supports test-driven development of Java code with mock objects.

Mock objects help you design and test the interactions between the objects in your programs.

The jMock library:

  • makes it quick and easy to define mock objects, so you don’t break the rhythm of programming.
  • lets you precisely specify the interactions between your objects, reducing the brittleness of your tests.
  • works well with the autocompletion and refactoring features of your IDE
  • plugs into your favourite test framework
  • is easy to extend.

image

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 will not affect the Mock Objects. So EasyMock is a perfect fit for Test-Driven Development.

Java mocking is dominated by expect-run-verify libraries like EasyMock or jMock.

Mockito offers simpler and more intuitive approach: you ask questions about interactions after execution. Using mockito, you can verify what you want. Using expect-run-verify libraries you are often forced to look after irrelevant interactions.

Mockito has similar syntax to EasyMock, therefore you can refactor safely. Mockito doesn’t understand the notion of ‘expectation’. There is only stubbing and verifications.

Mockito implements what Gerard Meszaros calls a Test Spy.

Some other features:

  • Mocks concrete classes as well as interfaces
  • Allows flexible verification in order (e.g: verify in order what you want, not every single interaction)
  • Supports exact-number-of-times and at-least-once verification
  • Flexible verification or stubbing using argument matchers (anyObject(), anyString() or refEq() for reflection-based equality matching)
  • Allows creating custom argument matchers or using existing hamcrest matchers
  • Verification errors are clean – click on stack trace to see failed verification in test; click on exception’s cause to navigate to actual interaction in code. Stack trace is always clean.
  • Little annotation syntax sugar – @Mock
  • Single-jar distribution mockito-all-1.6.jar includes cglib, objenesis and java source
  • Zip distribution mockito-1.6.zip contains all jars, javadoc and source


Trackback URL


Sorry, comments for this entry are closed at this time.