• Stars
    star
    440
  • Rank 95,333 (Top 2 %)
  • Language
    PHP
  • License
    Other
  • Created over 11 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tester: enjoyable unit testing in PHP with code coverage reporter. 🍏🍏🍎🍏

Nette Tester: enjoyable unit testing

Downloads this Month Tests Latest Stable Version License

Introduction

Nette Tester is a productive and enjoyable unit testing framework. It's used by the Nette Framework and is capable of testing any PHP code.

Documentation is available on the Nette Tester website. Read the blog for new information.

Support Tester

Do you like Nette Tester? Are you looking forward to the new features?

Buy me a coffee

Thank you!

Installation

The recommended way to install Nette Tester is through Composer:

composer require nette/tester --dev

Alternatively, you can download the tester.phar file.

  • Nette Tester 2.5 is compatible with PHP 8.0 to 8.2
  • Nette Tester 2.4 is compatible with PHP 7.2 to 8.2
  • Nette Tester 2.3 is compatible with PHP 7.1 to 8.0
  • Nette Tester 2.1 & 2.2 is compatible with PHP 7.1 to 7.3
  • Nette Tester 2.0 is compatible with PHP 5.6 to 7.3

Collecting and processing code coverage information depends on Xdebug or PCOV extension, or PHPDBG SAPI.

Writing Tests

Imagine that we are testing this simple class:

class Greeting
{
	function say($name)
	{
		if (!$name) {
			throw new InvalidArgumentException('Invalid name.');
		}
		return "Hello $name";
	}
}

So we create test file named greeting.test.phpt:

require 'src/bootstrap.php';

use Tester\Assert;

$h = new Greeting;

// use an assertion function to test say()
Assert::same('Hello John', $h->say('John'));

Thats' all!

Now we run tests from command-line using the tester command:

> tester
 _____ ___  ___ _____ ___  ___
|_   _/ __)( __/_   _/ __)| _ )
  |_| \___ /___) |_| \___ |_|_\  v2.5

PHP 8.2.0 | php -n | 8 threads
.
OK (1 tests, 0 skipped, 0.0 seconds)

Nette Tester prints dot for successful test, F for failed test and S when the test has been skipped.

Assertions

This table shows all assertions (class Assert means Tester\Assert):

  • Assert::same($expected, $actual) - Reports an error if $expected and $actual are not the same.
  • Assert::notSame($expected, $actual) - Reports an error if $expected and $actual are the same.
  • Assert::equal($expected, $actual) - Like same(), but identity of objects and the order of keys in the arrays are ignored.
  • Assert::notEqual($expected, $actual) - Like notSame(), but identity of objects and arrays order are ignored.
  • Assert::contains($needle, array $haystack) - Reports an error if $needle is not an element of $haystack.
  • Assert::contains($needle, string $haystack) - Reports an error if $needle is not a substring of $haystack.
  • Assert::notContains($needle, array $haystack) - Reports an error if $needle is an element of $haystack.
  • Assert::notContains($needle, string $haystack) - Reports an error if $needle is a substring of $haystack.
  • Assert::true($value) - Reports an error if $value is not true.
  • Assert::false($value) - Reports an error if $value is not false.
  • Assert::truthy($value) - Reports an error if $value is not truthy.
  • Assert::falsey($value) - Reports an error if $value is not falsey.
  • Assert::null($value) - Reports an error if $value is not null.
  • Assert::nan($value) - Reports an error if $value is not NAN.
  • Assert::type($type, $value) - Reports an error if the variable $value is not of PHP or class type $type.
  • Assert::exception($closure, $class, $message = null, $code = null) - Checks if the function throws exception.
  • Assert::error($closure, $level, $message = null) - Checks if the function $closure throws PHP warning/notice/error.
  • Assert::noError($closure) - Checks that the function $closure does not throw PHP warning/notice/error or exception.
  • Assert::match($pattern, $value) - Compares result using regular expression or mask.
  • Assert::matchFile($file, $value) - Compares result using regular expression or mask sorted in file.
  • Assert::count($count, $value) - Reports an error if number of items in $value is not $count.
  • Assert::with($objectOrClass, $closure) - Executes function that can access private and protected members of given object via $this.

Testing exceptions:

Assert::exception(function () {
	$h = new Greeting;
	$h->say(null);
}, InvalidArgumentException::class, 'Invalid name.');

Testing PHP errors, warnings or notices:

Assert::error(function () {
	$h = new Greeting;
	echo $h->abc;
}, E_NOTICE, 'Undefined property: Greeting::$abc');

Testing private access methods:

$h = new Greeting;
Assert::with($h, function () {
	// normalize() is internal private method.
	Assert::same('Hello David', $this->normalize('Hello david')); // $this is Greeting
});

Tips and features

Running unit tests manually is annoying, so let Nette Tester to watch your folder with code and automatically re-run tests whenever code is changed:

tester -w /my/source/codes

Running tests in parallel is very much faster and Nette Tester uses 8 threads as default. If you wish to run the tests in series use:

tester -j 1

How do you find code that is not yet tested? Use Code-Coverage Analysis. This feature requires you have installed Xdebug or PCOV extension, or you are using PHPDBG SAPI. This will generate nice HTML report in coverage.html.

tester . -c php.ini --coverage coverage.html --coverage-src /my/source/codes

We can load Nette Tester using Composer's autoloader. In this case it is important to setup Nette Tester environment:

require 'vendor/autoload.php';

Tester\Environment::setup();

We can also test HTML pages. Let the template engine generate HTML code or download existing page to $html variable. We will check whether the page contains form fields for username and password. The syntax is the same as the CSS selectors:

$dom = Tester\DomQuery::fromHtml($html);

Assert::true($dom->has('input[name="username"]'));
Assert::true($dom->has('input[name="password"]'));

For more inspiration see how Nette Tester tests itself.

Running tests

The command-line test runner can be invoked through the tester command (or php tester.php). Take a look at the command-line options:

> tester

Usage:
    tester [options] [<test file> | <directory>]...

Options:
    -p <path>                    Specify PHP interpreter to run (default: php).
    -c <path>                    Look for php.ini file (or look in directory) <path>.
    -C                           Use system-wide php.ini.
    -l | --log <path>            Write log to file <path>.
    -d <key=value>...            Define INI entry 'key' with value 'val'.
    -s                           Show information about skipped tests.
    --stop-on-fail               Stop execution upon the first failure.
    -j <num>                     Run <num> jobs in parallel (default: 8).
    -o <console|tap|junit|none>  Specify output format.
    -w | --watch <path>          Watch directory.
    -i | --info                  Show tests environment info and exit.
    --setup <path>               Script for runner setup.
    --temp <path>                Path to temporary directory. Default by sys_get_temp_dir().
    --colors [1|0]               Enable or disable colors.
    --coverage <path>            Generate code coverage report to file.
    --coverage-src <path>        Path to source code.
    -h | --help                  This help.

More Repositories

1

php-generator

🐘 Generates neat PHP code for you. Supports new PHP 8.3 features.
PHP
1,978
star
2

utils

🛠 Lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.
PHP
1,868
star
3

tracy

😎 Tracy: the addictive tool to ease debugging PHP code for cool developers. Friendly design, logging, profiler, advanced features like debugging AJAX calls or CLI support. You will love it.
PHP
1,712
star
4

nette

👪 METAPACKAGE for Nette Framework components
PHP
1,514
star
5

latte

☕ Latte: the safest & truly intuitive templates for PHP. Engine for those who want the most secure PHP sites.
PHP
1,044
star
6

finder

🔍 Finder: find files and directories with an intuitive API.
931
star
7

neon

🍸 Encodes and decodes NEON file format.
PHP
879
star
8

robot-loader

🍀 RobotLoader: high performance and comfortable autoloader that will search and autoload classes within your application.
PHP
854
star
9

di

💎 Flexible, compiled and full-featured Dependency Injection Container with perfectly usable autowiring and support for all new PHP 7 features.
PHP
841
star
10

schema

📐 Validating data structures against a given Schema.
PHP
811
star
11

bootstrap

🅱 The simple way to configure and bootstrap your Nette application.
PHP
654
star
12

forms

📝 Generating, validating and processing secure forms in PHP. Handy API, fully customizable, server & client side validation and mature design.
PHP
470
star
13

database

💾 A database layer with a familiar PDO-like API but much more powerful. Building queries, advanced joins, drivers for MySQL, PostgreSQL, SQLite, MS SQL Server and Oracle.
PHP
470
star
14

mail

A handy library for creating and sending emails in PHP
PHP
448
star
15

http

🌐 Abstraction for HTTP request, response and session. Provides careful data sanitization and utility for URL and cookies manipulation.
PHP
437
star
16

caching

⏱ Caching library with easy-to-use API and many cache backends.
PHP
390
star
17

application

🏆 A full-stack component-based MVC kernel for PHP that helps you write powerful and modern web applications. Write less, have cleaner code and your work will bring you joy.
PHP
384
star
18

security

🔑 Provides authentication, authorization and a role-based access control management via ACL (Access Control List)
PHP
338
star
19

component-model

⚛ Component model foundation for Nette.
PHP
251
star
20

routing

Nette Routing: two-ways URL conversion
PHP
220
star
21

sandbox

142
star
22

tokenizer

[DISCONTINUED] Source code tokenizer
PHP
141
star
23

safe-stream

SafeStream: atomic and safe manipulation with files via native PHP functions.
PHP
117
star
24

docs

📖 The Nette documentation
115
star
25

web-project

Standard Web Project: a simple skeleton application using the Nette
Latte
102
star
26

reflection

[DISCONTINUED] Docblock annotations parser and common reflection classes
PHP
94
star
27

examples

🎓 Examples demonstrating the Nette Framework.
88
star
28

code-checker

✅ A simple tool to check source code against a set of Nette coding standards.
PHP
85
star
29

web-addons.nette.org

[DISCONTINUED] Website https://addons.nette.org source code.
PHP
55
star
30

coding-standard

Nette Coding Standard code checker & fixer
PHP
40
star
31

command-line

⌨ Command line options and arguments parser.
PHP
37
star
32

type-fixer

🆙 A tool to automatically update typehints in your code.
PHP
29
star
33

resources

Client-side resources for Nette Framework.
23
star
34

latte-tools

Twig & HTML to Latte converters
PHP
22
star
35

grunt-nette-tester

Grunt plugin for Nette Tester
JavaScript
20
star
36

middleware

PHP
20
star
37

deprecated

[DISCONTINUED] APIs and features removed from Nette Framework
PHP
19
star
38

safe

🛡 PHP functions smarten up to throw exceptions instead of returning false or triggering errors.
PHP
17
star
39

nette-minified

[DISCONTINUED] Minified version of Nette Framework.
PHP
16
star
40

tutorial-todo

[DISCONTINUED] Tutorial for simple task manager.
PHP
10
star
41

union

[READ-ONLY] Subtree union of Nette repositories
PHP
7
star
42

assistant

PHP
3
star
43

.github

1
star