/ phpunit

Getting Started with PHPUnit 7 using composer

PHPUnit is a unit testing framework for the PHP programming language.
It is an instance of the xUnit architecture for unit testing frameworks that originated with SUnit and became popular with JUnit.
PHPUnit was created (2004) by Sebastian Bergmann and its development is hosted on GitHub

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct.

Getting Started with PHPUnit 7

Note:This tutorial assumes that you use PHP 7.1 or PHP 7.2. You will learn how to write simple unit tests as well as how to download and run PHPUnit.

Installation

Composer

The option --dev -> Add packages to require-dev, packages that aren't necessary for your project to work and shouldn't be included in the production version
Including the ^version: means "Compatible with version"

composer require --dev phpunit/phpunit "^7"
./vendor/bin/phpunit --version
PHPUnit 7.4.4 by Sebastian Bergmann and contributors.

or without option --dev

composer require phpunit/phpunit
./vendor/bin/phpunit --version
PHPUnit 7.4.4 by Sebastian Bergmann and contributors.

Note:
The example shown above assumes that composer is on your $PATH.

Your composer.json should look similar to this:

{
  "autoload": {
    "classmap": [
      "src/"
    ]
  },
  "require-dev": {
    "phpunit/phpunit": "^7"
  }
}

Before generating the autoloader, we can create an application and tests folders:

mkdir src
mkdir tests

Test Suites and first test

The element and its one or more children can be used to compose a test suite out of test suites and test cases.
Example of a simple file (located on the root project) phpunit.xml:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
  colors="true"
  verbose="true"
  stopOnFailure="false">
  <testsuites>
    <testsuite name="tests">
      <directory>tests</directory>
    </testsuite>
  </testsuites>
</phpunit>

Next, create our first test:
tests/UrlTest.php

Add inside of the file UrlTest.phpthe following:

<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

class URLTest extends TestCase
{
    public function testSluggifyReturnsSluggifiedString()
    {
        $originalString = 'My string to be sluggified';
        $expectedResult = 'my-string-to-be-sluggified';

        $url = new URL();
        $result = $url->sluggify($originalString);
        $this->assertEquals($expectedResult, $result);
    }
}

For the file src/Url.php, we will add the following content:

<?php
declare(strict_types=1);

class URL
{
    public function sluggify($string, $separator = '-', $maxLength = 96)
    {
        $title = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
        $title = preg_replace("%[^-/+|\w ]%", '', $title);
        $title = strtolower(trim(substr($title, 0, $maxLength), '-'));
        $title = preg_replace("/[\/_|+ -]+/", $separator, $title);

        return $title;
    }
}

Then update composer, generating the autoloader using composer update -o or composer dump-autoload -o.

The -o (short of --classmap-authoritative) tells Composer to scan the directories declared in composer.json (src/) in our case and create a classmap that contains all the classes it can find.

So to generate optimised autoload files, just need to run:
composer dump-autoload -o

By running the next command:
./vendor/bin/phpunit or
./vendor/bin/phpunit --bootstrap vendor/autoload.php --testdox tests
We should have the following next output:

PHPUnit 7.4.4 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.1.19
Configuration: /Applications/MAMP/htdocs/Phpunit/phpunit_composer_v4/phpunit.xml

URL
 ✔ Sluggify returns sluggified string [1.98 ms]

Time: 20 ms, Memory: 4.00MB

OK (1 test, 1 assertion)

Conventions

PHPUnit has a few conventions to make your life easier.
You do not necessarily have to follow them if you want to do things slightly differently, but for our purposes we are going to stick to them.

File structure and filenames

The first convention we will discuss is the file structure and filenames.
Your tests should mirror your codebase directly but within its own folder, and test files must match the file they are testing, with Test appended. In our example, if we had the following code:

./src/Url.php

Our tests would be structured as:

./tests/UrlTest.php

Classnames

Classnames are exactly the same as filenames. Whatever you have named your file should be the name of your class - which should be true for your non-test code anyway!

Method (test) names

Your test method names should start with test, in lower case. Method names should be descriptive of what is being tested, and should include the name of the method being tested. This is not a place for short, abbreviated method names.

For example, if you are testing a method called verifyEmailAccount(), and in one unit test you want to test that the password matches, you would name your test testVerifyEmailAccountMatchesPasswordGiven().

Verbosity is a boon when testing, because when you have a failing test, and you will have many failing tests, you will be appreciative of seeing the method name and knowing exactly what failed.

Methods must be public

PHPUnit is unable to run tests that are either protected or private - they must be public. Likewise, any methods you create as helpers must be public. We are not building a public API here, we just want to write tests so do not worry about visibility.

Extends PHPUnit

Your classes must extend the PHPUnit_Framework_TestCase class, or extend a class that does.
Examples:

...
 class UrlTest extends \PHPUnit_Framework_TestCase
 {
		//
 }

or

...
 class UrlTest extends PHPUnit\Framework\TestCase
 {
		//
 }
Getting Started with PHPUnit 7 using composer
Share this

Subscribe to NL Slack