PHPUnit tests real example

thom picture thom · Jun 14, 2011 · Viewed 20.5k times · Source

I've created a mail wrapper class. I know that there are lots of libraries to send e-mails but i want to learn TDD... So, I've created some tests and i have some code. Now I can set the email address on constructor and validate it... if the email address is wrong, an exception raise up. The email address is the only one required field... I don't have sets and gets because user will setup all email data on constructor.

Now, i'm going to write the send tests. I don't know how to start it. How could i test if the values are there (subject, mail body, headers) if i don't want to have setters and getters? How could I test if an email could be sent?

Real world TDD examples are hard to me. I've tried to learn about it, i've read lots of things but i cannot test real code.

Thanks.

Answer

Gordon picture Gordon · Jun 14, 2011

Since you linked to the mail function, the call to mail is likely hardcoded into your code. So have a look at

Install the testhelper extension and mock the call to mail. Then have the mock validate that it got called with the correct values when your wrapper's send method is called, e.g. define a custom mail function somewhere:

function mail_mock()
{
    $allThatWasPassedToTheFunction = func_get_args();
    return $allThatWasPassedToTheFunction;
}

Then in your send() test, do something like

public function testSendReceivesExpectedValues()
{
    // replace hardcoded call to mail() with mock function
    rename_function('mail', 'mail_orig');
    rename_function('mail_mock', 'mail');

    // use the wrapper
    $testClass = new MailWrapper('[email protected]');
    $results = $testClass->send();

    // assert the result
    $this->assertSame('[email protected]', $results[0]);
    $this->assertSame('Default Title', $results[1]);
    $this->assertSame('Default Message', $results[2]);
}

Note that the above assumes your send function will return the result of the mail() call.

In general, you will always try to substitute an external subsystem, like sendmail or a database or the filesystem with a Mock or a Stub, so you can concentrate on testing your own code in isolation of the external subsystem. You dont need to test that mail actually works.

Also see http://www.phpunit.de/manual/3.6/en/test-doubles.html