March 19, 2018

TDD terms: What is a stub or test double?

When it comes to test driven development, there are a lot of terms.

And the list continues.

This post is the first in a series that will go through the common terms used, and explain what they mean.

First up is “Stub” (also referred to as a “Test Double”).

A stub is a fake object that takes the place of a real object when running a test.

Let’s say we have a feature that allows the user to reset their password. When they reset their password we email them a temporary password.

Since we’re running a test, we don’t want to send a real email, so we can create a stub that will “send an email”.

The stub.

interface MailInterface 
    public function send($email);

class MailStub implements MailInterface
    private $sent_messages = [];

    public function send($email) 
        array_push($sent_messages, $email);     

    public function numberOfEmailsSent($email) 
        return count($sent_messages);       

Quick side note

(If you know what an interface is skip to the next code block)

If you’re unsure of what an interface is, think of it as a contract between two people. Every person that signs the contract is bound by the terms of the contract.

Similarly, every class that implements an interface must contain the same methods as the interface.

In our case the MailInterface has a send method, therefore MailStub class must have a send method.

Back to the show.

Our test:

public function send_user_a_temporary_password_when_they_reset_their_password {
    $user = new User(';

    $mailer = new MailStub;


    $this->assertEquals(1, $mailer->numberOfEmailsSent());

What $user->resetPassword($mailer) does, we don’t really care.

We can pass in any mailer object that implements the interface MailInterface and be confident that we are testing something of value, because both MailStub and any real mailer class must contain the send method.

Well, there you have it. You now have some idea of what a stub is.

If you have any questions, you can email me at or @spangnation

Are you new to Test Driven Development?

Join the mailing list! :)