Testing with Mocks

Testing with Mocks


Posted in : Java Posted on : November 30, 2010 at 1:29 PM Comments : [ 0 ]

This section contains the details about Testing with Mocks.

Testing with Mocks

A Mock is like a stub, only it also has methods that make it possible determine what methods where called on the Mock.

Using a mock it is thus possible to test both-if the unit can handle various return values correctly, and also if the unit uses the collaborator correctly.

For instance, you cannot see by the value returned from a dao object whether the data was read from the database using a Statement or a PreparedStatement. Nor can you see if the connection.close() method was called before returning the value. This is possible with mocks.

In other words, mocks makes it possible to test a units complete interaction with a collaborator. Not just the collaborator methodsthat return values used by the unit. Steps involving in using a mock in a unit test could be expressed like this :

Step 1: First the unit test creates the mock and configures its return values.

                                            unit test --> mock

Step 2: Then the unit test creates the unit and sets the mock on it. Now the unit test calls the unit which in turn calls the mock.

                                           unit test --> unit --> mock

Step 3: The unit test makes assertions about the results of the method calls on the unit.

Step 4: The unit test also makes assertions on what methods were called on the mock.

Example

In this example, we wanted to send an email message if we failed to fill an order. The problem is that we don't want to send actual email messages out to customers during testing. So instead we create a test double of our email system, one that we can control and manipulate.

We might write a simple stub like this :

class OrderInteractionTester...
public void testOrderSendsMailIfUnfilled() {
Order order = new Order(TALISKER, 51);
Mock warehouse = mock(Warehouse.class);
Mock mailer = mock(MailService.class);
order.setMailer((MailService) mailer.proxy());
mailer.expects(once()).method("send");
warehouse.expects(once()).method("hasInventory")
.withAnyArguments()
.will(returnValue(false));
order.fill((Warehouse) warehouse.proxy());
}
}
Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics