bookmark_borderEasyMock and Mockito, a little comparison

Someone mentioned a mocking framework called Mockito some time ago to me. I am familiar with mocking frameworks, as I work with EasyMock quite a lot. I really like EasyMock, but I am curious about Mockito. I thought of trying it out a bit and write down my experiences along with a comparison with EasyMock.

This is by all means not a very in-depth comparison, but I did find out some interesting things.

In order to test out the mocking frameworks I have set up some code in place to test. The code to be tested is an ‘itemRepository’ (It is however, not a full implementation of the Repository Pattern). Typically you use it to get some stuff (Items). In this case the Item is retrieved from a Dao object used by the repository. Just for easiniess the DAO returns the same object as the repository. (The repository pattern makes a distinction between the object the DAO returns and the Domain objects the Repository should return).

Here is the code of the ItemRepository:

public class ItemRepositoryImpl implements ItemRepository {

	private ItemDao itemDao;
	
	@Override
	public Item getItem(String someInput) {
		return itemDao.getById(Long.valueOf(someInput));
	}

	public void setItemDao(ItemDao itemDao) {
		this.itemDao = itemDao;
	}

	public ItemDao getItemDao() {
		return itemDao;
	}

}

My goal is to test the ItemRepository’s getItem method. And all I care about is that the itemDao is correctly called with the correct parameters. Hence this is what a collaboration test is all about.

Lets start with my comfort zone: EasyMock

The test class I write talks to interfaces. I find it a good habit to talk against interfaces and not concrete implementations. Doing that however, forces me to cast to an implementation to set collaborators in the tests. Normally such things happen in the @Before. But since I will also create a test with the Mockito framework I have it done in the test method itself.

The begin of the test:

public class ItemRepositoryTest {

	private ItemRepository itemRepository;
	private ItemDao itemDao;
	
	@Before
	public void setUp() {
		itemRepository = new ItemRepositoryImpl();
	}

In line of the tripple A testing guidelines I have an arrange, act and assert:

	@Test
	public void mustReturnItemFromMockedItemDao_EasyMock_Behaviour() {
		ItemRepositoryImpl impl = getItemRepository();
		itemDao = EasyMock.createMock(ItemDao.class);
		impl.setItemDao(itemDao);
		
		// this is weird: I don't *want* to bother about returning stuff here, just that it is called!
		// mocking and stubbing is combined here
		EasyMock.expect(itemDao.getById(1L)).andReturn(null); 
		EasyMock.replay(itemDao);
		
		// Act
		itemRepository.getItem("1");
		
		// Verify
		EasyMock.verify(itemDao);
	}

As you can see I have pointed out one thing of EasyMock’s behaviours with a comment. Whenever you mock a method that has a return type, EasyMock expects you to fill in that behaviour. If you don’t do that, you’ll end up with an exception like this:

java.lang.IllegalStateException: missing behavior definition for the preceding method call getById(1)

In this case I have ‘solved’ it by returning null. While writing the test, I did not want to be bothered about it, but I have to satisfy EasyMock. Doing so reduces the readability of my code. The intention of the code remains unclear at this point, and that’s something I’d like to avoid as much as I can.

Another well known behaviour of EasyMock is the need to replay your mock after you have set the expectations. Using a ‘recorder’ metaphor it sounds reasonable. But basically you’re writing the behaviour ‘twice’: First you write down the expectations, then you actually run them. Writing the expectations is often found to be a cumbersome job to do, especially with multiple collaborators.

And of course at the end it all needs to be verified. Which is done by EasyMock.verify. We could even check the outcome. Most of the time you’re tempted to do so, you had to write the return value anyway. Better test if the return value being returned is the same as the method returns right? I think not. Reason: your intention of your test becomes unclear if you assert this as well. And as a bonus you introduce your tests to be more fragile. The unit test becomes now a collaborator test and a value-based test in one. Mockito makes this distinction very clear.

Mockito:

	@Test
	public void mustReturnItemFromMockedItemDao_Mockito_Behaviour() {
		// Arrange
		ItemRepositoryImpl impl = getItemRepository();
		itemDao = Mockito.mock(ItemDao.class);
		impl.setItemDao(itemDao);

		// Act
		itemRepository.getItem("1");
		
		// Assert / verify
		Mockito.verify(itemDao).getById(1L);
	}

Plus:
– no need to mock return etc, as we dont care
– seperation of mocking and stubbing (stubbing is done by using the static method when, mocking by using verify).

So how about stubbing in Mockito? Here is how you stub the itemDao:

	@Test
	public void mustReturnItemFromMockedItemDao_Mockito_Stubbing() {
		// Arrange
		ItemRepositoryImpl impl = getItemRepository();
		itemDao = Mockito.mock(ItemDao.class);
		impl.setItemDao(itemDao);

		Mockito.when(itemDao.getById(1L)).thenReturn(null);
		
		// Act
		itemRepository.getItem("1");		
	}

For more information about Mockito, they also have a more extensive comparison between EasyMock and Mockito.

Do you have any experience using Mockito and EasyMock and you would like to share some insights? Please leave a comment.

Someone pointed at RhinoMocks also being available for Java. I’m not so sure about that. However, if you do know about a Java variant, let me know so I can compare it as well.

bookmark_borderHow to fry your co-developers brain; and then make it better

Here is a little example of code I’ve been faced with (not written by me), that struck me. Although the syntax is correct (it is javascript), it took me a little while to actually understand what is going on.

Here is the code:

someObject: function(data) {
	  return data.json ? data.json.stateObject ? data.json.stateObject : {} : {};
},

And here is how I refactored it.

   someObject: function(data) {                  
		  if (data.json) {
				if (data.json.stateObject) {
					return data.json.stateObject;
				}
		  }
		  return {};                             
   }

So I mentioned brianpower in a while ago. Michael Feathers though calls such a thing “forming a mental model“. Which is exactly what I meant. You also hear this in the scene of Usability; the less your mental model matches with the actual object you use (expectations), the less likely you’ll probably understand it, let alone *use it*.

So tell me, which one is easier to understand? And how much impact do you think this has?

bookmark_borderTiny refactorings? Compose Method!

I blogged about tiny refactorings not too long ago. I’ve even added an example showing such a refactoring in my game.

I’m reading Refactoring to Patterns, and figured that the refactorings I’ve mentioned have a name; it’s called the Compose Method. In the book it even has its own chapter (Chapter 7 “Simplification”), where it also refers to other great patterns to help you improve your maintainability of your code.

bookmark_borderCreating (default) test instances of a class, without exposing default constructor.

Did you ever need to just have an instance of a class you cannot instantiate because the default constructor is not available? Do you want to create a test instance just to be used in unit tests? Don’t want to break up the design of your code just for testing? This post might help you:

Sample code:


public MyClass {
final int someField;

private MyClass() {
// may not use this
someField = -1;
}

public MyClass(int someFieldValue) {
someField = someFieldValue;
}

int getSomeField() {
return someField;
}
}

So lets say this class is used in a lot of places. And all we want is have a default test instance. We don’t care about the internals. Lets say we only use it to toss around using an interface which we mock in our tests. Like so:


public void someUnitTestUsingMyClassAndMockingAnInterface() {
MyClass instance = new MyClass(-1); // this works, but its not really descriptive
MyClass someotherMyClass = new MyClass(-1); // like, what is -1? we don't want to be bothered by this
EasyMock.expect(someinterface.doSomethingWithMyClass(instance)).andReturn(someotherMyClass);
...
}

There are two ways to approach this problem:

  • Make private constructor public
  • Use a Factory or a creation method

So, just making the default constructor public sounds easy and is used very often. And, because we want to let our fellow developers know it is just to be used in unit-tests we place a comment in them. This mostly results in something like this:


public MyClass {
final int someField;

public MyClass() {
// Use this only in tests!
someField = -1;
}

}

However, this has a few drawbacks:

  • You cannot see if the default constructor should only be used for tests, unless you look into the code itself and read that comment line
  • You broke with the initial design decision to have only objects instantiated with a given “someField”

So how do we prevent this?

We use a factory, or a creation method. Lets start with the first, the factory: If there is a factory, just use it to get a test instance. If the factory lacks a ‘createTestInstance()’ method, then add it. Like so:

public MyClassFactoryImpl implements MyClassFactory {

public MyClass createTestInstance() {
return new MyClass(-1);
}

}

We could discuss about wether you want the method to be factory method to be static here, and so forth, but the idea is clear.

However, when there is no factory present it is unlikely you want to create a factory just for your unit tests. In that case I suggest you use the creation method, also refered to as the factory method pattern. Simply add a public static method that returns a new instance. The final result would be:

public MyClass {
final int someField;

public static MyClass createTestInstance() {
return new MyClass();
}

private MyClass() {
// may not use this
someField = -1;
}

public MyClass(int someFieldValue) {
someField = someFieldValue;
}

int getSomeField() {
return someField;
}
}

The benefits are clear:

  • The default constructor remains private, so the design is left untouched
  • It is clear what the createTestInstance method does. No comments needed.

And in your unit test (using EasyMock as well) it looks like this:


public void someUnitTestUsingMyClassAndMockingAnInterface() {
MyClass instance = MyClass.createTestInstance();
MyCLass someotherMyClass = MyClass.createTestInstance();
EasyMock.expect(someinterface.doSomethingWithMyClass(instance)).andReturn(someotherMyClass);
...
}

Note: When you wind up with multiple create methods you should consider using the Factory pattern instead. Yes, creating a factory is the best thing once creation logic starts to dominate your class. (ie, think of the Single Responsibility Principle).
Note 2: If you’re a design purist, you might even debate that the public constructor of MyClass should be a creation method. It improves consistency as all instances are created by creation methods. It also has the benefit of describing what kind of instance you get (ie, what the field means). Such improvements are valid and should be made. I consider these improvements small refactorings. They should never be undervalued.

bookmark_borderThe tremendous power of tiny refactorings

More and more I am being intrigued by the power of a small code refactorings. The positive impact it has on the readability, the maintainability and understandability of your code is great. It keeps code clean(er) and since the changes you make are really small (I’ll demonstrate how small), the chance they will break things is small. Of course, with unit tests (you are writing them right?) making sure you did not break anything: a small refactoring is a low-risk high-benefit practice.

In my experience, small refactorings are undervalued. In fact, I undervalued them much myself since not too long ago. They are disregarded as refactorings that don’t help at all, because it is obvious what the code does. However, the flaw in this rationale, as I see it, is that the intended audience is not only you but also the other developer you work with. Also, you know what code does right now. But would you understand it as quickly if you did not look at it for a week and came back? Would another developer understand the code right away?

When working on code, you’re constantly trying to ‘translate’ the code in your mind in order to know what it is doing. Doing this it leads you to where the bugs are or the areas where you need to make changes, etcetera. This process of ‘translating’ code in your mind comes at a price. Literally the energy you need to burn in your brain to grasp the meaning of a piece of code: brainpower; The easier we understand code, the less brainpower we need. The less energy we burn by understanding what is going on, the more energy we have left to create new things, or fix that bug.

I’ve created a little example. The code below represents an implementation of a mail service. The mail service allows you to send an email using a method that uses 4 parameters: to, from, the subject and the message. When all parameters are filled, the email needs to be sent. That is the only requirement for now. Of course, later we might want to validate if the given email adress of from and to are valid. But for the sake of the argument, lets keep it simple. The following code is ‘mind-boggling’, compared to its simple intention:

public class MailServiceImpl implements MailService {

	public void sendMail(String from, String to, String subject, String message) {
		if (from != null && !"".equals(from) &&
			to != null && !"".equals(to) &&
			subject != null && !"".equals(subject) &&
			message != null && !"".equals(subject)) {
			// send the email
		}
	}

}

Basically what this says it that any field may not be null or an empty string. It took 4 lines for just to show. Even though you recognize the pattern of a ‘null or empty check’, it costs you time and energy to make that translation happen. So here is a first suggestion to make it read easier:

public class MailServiceImpl implements MailService {

	public void sendMail(String from, String to, String subject, String message) {
		if (parametersAreNotNullOrEmpty(from, to, subject, message)) {
			// send the email
		}
	}

	private boolean parametersAreNotNullOrEmpty(String from, String to, String subject,
			String message) {
		return from != null && !"".equals(from) &&
			to != null && !"".equals(to) &&
			subject != null && !"".equals(subject) &&
			message != null && !"".equals(subject);
	}

}

When another developer is reading the sendMail method, he will now know that when the parametersAreNotNullOrEmpty the mail will be sent. It does not need any translation, the method name just says what it does! Simple! By doing this, you greatly reduce the needed brainpower to understand what is going on. The refactoring method used is called Extract method.

Reading code is sometimes easy for your brain to handle. Sometimes your brain seems to explode because of the complex statements and context you need to be aware of. It is strongly tied with the Cyclomatic Complexity, the Coupling between Objects (CBO) and the lack of Cohesion in your code. If you are using any tools to measure your code, like Sonar for example, look for these metrics to find code that needs attention. But it is always better to refactor while you have made the translation in your brain, if you see things can be written simpler to reduce the needed brainpower, by all means do so. Not giving software the appropriate attention might let your code rot. Small refactorings help you prevent that.

I hope you have seen a bit of the power of small refactorings. I will get back to them in my future posts as I will post more concrete examples and how I would/have dealt with them. To me, small refactorings need to be part of your system and are introduced when you do TDD. All too often when the code works, it is not looked at again. Making these small refactorings can make a big difference and take relatively no time.