Posts mit dem Label Mocking werden angezeigt. Alle Posts anzeigen
Posts mit dem Label Mocking werden angezeigt. Alle Posts anzeigen

Samstag, 10. Dezember 2011

Mockito the Java Standard Mocking Framework?

I used a long time JMock and I really love it, I also used a lot EasyMock because of the answer and capture feature. About a year ago I found the mocking framework mockito. After that I was able to inspire a few work colleagues to use mockito in their projets. I play around with it again and my conclusion is: Mockito is at the moment the best mocking framework for Java and I'm not alone.

"We decided during the main conference that we should use JUnit 4 and Mockito because we think they are the future of TDD and mocking in Java" - Dan North, the originator of BDD

Mockito has a clean syntax and the patterns and ideas behind mockito make tests more maintainable. Mockito has the power of EasyMock but a smarter syntax. Today I build for my self a simple JUnit test as mockito cheat sheet. So you convince yourself with Mockito and the smart API see the demo test bellow.


Links
  • Mockito Project Site
    http://code.google.com/p/mockito/
  • Documentation Mockito
    http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html
  • GitHub Project with the Cheat Sheet Test
    https://github.com/tux2323/mockito-cheat-sheet

Mittwoch, 23. November 2011

Test Doubles and Mocking Patterns

Yesterday I refactored a unit test with over 2000 lines of code, now the test has around 900 lines of code. One pattern I found in the test was that for every kind of test double a mock object was used.

I prefer the following test design rule for mock objects and test doubles. Object which contains logic e.g. of type service, factory or repository should be mocked instead of DTOs, value objects or entities (plain Java Beans) with getters and setters e.g. configuration objects this kind of object should never be mocked.

Here small example, a test with to much mocking, please don't write such kind of tests:


This simple unit test above has to much mocking logic and should be refactored to this test:


If you like you could use the builder pattern for the simple objects like sale to get the test a little bit nicer (see the links for eclipse tooling). A smell is when you need to mock classes, in most cases then you should use another test double pattern for this kind of objects, or something with the design of the SUT is wrong.

What I like to say is you should not always use our preferred mocking framework to create a mock object as test double for everything. There are situations where mock object I believe are a test design anti pattern / smell. Think about stubs and dummy object before creating a mock object and read the great xUnit test pattern book “xUnit Test Patterns” from Gerard Meszaros. Then you are on the right way to get an agile tester ;-)

Links