Testing with Stubs

Testing with Stubs


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

This section contains the details about Testing with Stubs.

Testing with Stubs

A Stub is an object that implements an interface of a component, but instead of returning what the component would return when called, the stub can be configured to return a value that suits the test.

Using stubs a unit test can test if a unit can handle various return values from its collaborator.

Steps involving in using a stub instead of a real collaborator in a unit test could be expressed like this :

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

                                    unit test --> stub

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

                unit test --> unit --> stub

Step 3 : Finally the unit test makes assertions about the results of the method calls on the unit and state of unit.

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 :

public interface MailService {
public void send (Message msg);
}
public class MailServiceStub implements MailService {
private List<Message> messages = new ArrayList<Message>();
public void send (Message msg) {
messages.add(msg);
}
public int numberSent() {
return messages.size();
}
}

Now, We can make assertions about the results of the method calls on the unit and state of unit like this:

class OrderStateTester...
public void testOrderSendsMailIfUnfilled() {
Order order = new Order(TALISKER, 51);
MailServiceStub mailer = new MailServiceStub();
order.setMailer(mailer);
order.fill(warehouse);
assertEquals(1, mailer.numberSent());
}

 

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics