PHPUnit

From XennisWiki
Jump to: navigation, search

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. (Wikipedia)

Usage

Further information: PHPUnit Getting Started guide

In the composer.json add PHPUnit as development dependency. Add the classmap path as well (here it's src/main/php).

{
    "autoload": {
        "classmap": [
            "src/main/php"
        ]
    },
    "require-dev": {
        "apigen/apigen": "4.1.*",
        "phpunit/phpunit": "7.4.*"
    }
}

The file that should be tested: src/test/php/model/File.php

<?php
class Admin_Model_File {

	/**
	 * Returns for a name a path, i.e. removes special characters.
	 * 
	 * @param string $name
	 * @return string Path
	 */
	public static function nameToPath($name) {
		// Remove space in the front/end and make it lowercase
		$name = strtolower(trim($name));
		// Search and replace specific characters
		$name = strtr($name, array(
			' ' => '_',
			'-' => '_',
                        '/' => '_',
			'ä' => 'ae',
			'ö' => 'oe',
			'ü' => 'ue',
			'ß' => 'ss'
		));
                // Replace all characters except letters, numbers, spaces and underscores
                $name = preg_replace('/[^ \w]+/', '', $name);
                //Remove multiple whitespaces
                return preg_replace('/_+/', '_', $name);
        }
}

The tests in src/test/php/model/FileTest.php

<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

class FileTest extends TestCase {
    
    public function testNameToPath() {
        $this->assertNameToPath(' FuU   bAr ', 'fuu_bar');
        $this->assertNameToPath(' -/', '_');
    }
    
    private function assertNameToPath(String $pattern, String $result) {
        $this->assertEquals($result, Admin_Model_File::nameToPath($pattern));
    }
}

Finally run the test

./vendor/bin/phpunit --bootstrap vendor/autoload.php src/test/php/

Mock

Create a mock from builder

Exemplary mock creation

$mock= $this->getMockBuilder('wpdb')
            ->setMethods(array('get_charset_collate'))
            ->getMock();
$mock->prefix = 'wp_';
$mock->method('get_charset_collate')
      ->willReturn('charset');

See also

External links