Test the website

Now that we have a fully functional website, including a simple API, let's make sure it stays that way with some automated tests.

For this, we will use the fakes extension together with PHPUnit.

Create a test

Create the directory Tests/ and in that directory, add the file WebsiteTest.php with the following content:

<?php declare(strict_types=1); namespace Tests; use Application\Setup\ApplicationSetup; use BlueMvc\Fakes\FakeRequest; use BlueMvc\Fakes\FakeResponse; use BlueMvc\Fakes\FakeApplication; use PHPUnit\Framework\TestCase; require_once __DIR__ . '/../vendor/autoload.php'; class WebsiteTest extends TestCase { function testIndexPage() { $application = new FakeApplication(__DIR__ . '/../'); ApplicationSetup::setup($application); $request = new FakeRequest('/'); $response = new FakeResponse(); $application->run($request, $response); $this->assertContains('Foo', $response->getContent()); } }

Note that this code looks very similar to the BlueMvc bootstrap code found in index.php in the web root. We are actually emulating the real workflow, but with test-friendly fake classes instead.

Run the test

Run the following command from the command prompt where /path/to/webroot is the path to the web root.

$ phpunit /path/to/webroot/Tests/WebsiteTest.php

The result should look similar to this:

Failed asserting that '<!DOCTYPE html>\n ... </html>' contains "Foo". ... FAILURES! Tests: 1, Assertions: 1, Failures: 1.

Well, that was expected. The index page does not contain the word "Foo" anywhere.

What is more interesting is that the fake classes helped us to test our website without the need to actually fetch the content via http from the web server.

Feel free to prove it by disabling the web server and run the test again.

Pass the test

Let's fix the test to make it pass, while also make sure that the status code in the response is 200.

Open Tests/WebsiteTest.php and modify the testIndexPage method to look like this:

function testIndexPage() { $application = new FakeApplication(__DIR__ . '/../'); ApplicationSetup::setup($application); $request = new FakeRequest('/'); $response = new FakeResponse(); $application->run($request, $response); $this->assertContains('BlueMvc', $response->getContent()); $this->assertSame(200, $response->getStatusCode()->getCode()); }

Re-run the test:

$ phpunit /path/to/webroot/Tests/WebsiteTest.php

This time the result should look like this:

OK (1 test, 2 assertions)

That was a little insight into the fakes extension and also the last hands-on part of this tutorial.

We will finish this tutorial in the next part with a brief conclusion.

✎ Published in category get started