Home Backend Development PHP Tutorial Basic use of PHP testing framework PHPUnit

Basic use of PHP testing framework PHPUnit

May 07, 2020 am 09:49 AM
monolog php phpunit

1. Foreword

In this article, we use composer’s dependency package management tool to install and manage phpunit packages. Composer’s official address is https: //getcomposer.org/, just follow the prompts to install it globally. In addition, we will also use a very easy-to-use Monolog logging component to record logs for our convenience.

Create the configuration file of coomposer.json in the root directory and enter the following content:

{
    "autoload": {
        "classmap": [
            "./"
        ]
    }
}
Copy after login

The above means to load all the class files in the root directory and execute it on the command line After composer install, a vendor folder will be generated in the root directory. Any third-party code we install through composer in the future will be generated here.

2. Why unit testing?

Any time you think of typing something into a print statement or debug expression, replace it with a test. --Martin Fowler

PHPUnit is an open source software developed in the PHP programming language and is a unit testing framework. PHPUnit was created by Sebastian Bergmann, derived from Kent Beck's SUnit, and is one of the frameworks of the xUnit family.

Unit testing is the process of testing individual code objects, such as testing functions, classes, and methods. Unit testing can use any piece of test code that has been written, or you can use some existing testing frameworks, such as JUnit, PHPUnit or Cantata. The unit testing framework provides a series of common and useful functions to help people write automated detection units. , such as an assertion that checks whether an actual value matches the expected value. Unit testing frameworks often include reports for each test and give you the code coverage you have covered.

In a word, using phpunit for automatic testing will make your code more robust and reduce the cost of later maintenance. It is also a relatively standard specification. Today's popular PHP frameworks all come with unit testing. Such as Laraval, Symfony, Yii2, etc., unit testing has become standard.

In addition, unit test cases control the test script through commands instead of accessing the URL through the browser.

3. Install PHPUnit

Use composer method to install PHPUnit. For other installation methods, please see here

composer require --dev phpunit/phpunit ^6.2
Copy after login

Install Monolog log Package, used for phpunit testing and logging.

composer require monolog/monolog
Copy after login

After installation, we can see that the coomposer.json file already has these two expansion packages:

"require": {  
     "monolog/monolog": "^1.23",
    },
"require-dev": {
        "phpunit/phpunit": "^6.2"
    },
Copy after login

4. Simple usage of PHPUnit

1. Single file test

Create the directory tests, create a new file StackTest.php, edit it as follows:

<?php
/**
 * 1、composer 安装Monolog日志扩展,安装phpunit单元测试扩展包
 * 2、引入autoload.php文件
 * 3、测试案例
 *
 *
 */
namespace App\tests;
require_once __DIR__ . &#39;/../vendor/autoload.php&#39;;
define("ROOT_PATH", dirname(__DIR__) . "/");
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
    public function testPushAndPop()
    {
        $stack = [];
        $this->assertEquals(0, count($stack));
        array_push($stack, &#39;foo&#39;);
        // 添加日志文件,如果没有安装monolog,则有关monolog的代码都可以注释掉
        $this->Log()->error(&#39;hello&#39;, $stack);
        $this->assertEquals(&#39;foo&#39;, $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));
        $this->assertEquals(&#39;foo&#39;, array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
    public function Log()
    {
        // create a log channel
        $log = new Logger(&#39;Tester&#39;);
        $log->pushHandler(new StreamHandler(ROOT_PATH . &#39;storage/logs/app.log&#39;, Logger::WARNING));
        $log->error("Error");
        return $log;
    }
}
Copy after login

Code explanation:

StackTest is a test class

StackTest inherits from PHPUnit\Framework\TestCase

The test method testPushAndPop(), the test method must have public permissions, usually starting with test, or you can choose Annotate it with @test to indicate

Within the test method, assertion methods similar to assertEquals() are used to assert that the actual value matches the expected value.

Command line execution:

phpunit command test file naming

➜  framework#  ./vendor/bin/phpunit tests/StackTest.php
// 或者可以省略文件后缀名
//  ./vendor/bin/phpunit tests/StackTest
Copy after login

Execution results:

➜  framework# ./vendor/bin/phpunit tests/StackTest.php
PHPUnit 6.4.1 by Sebastian Bergmann and contributors.
.                                                                   1 / 1 (100%)
Time: 56 ms, Memory: 4.00MB
OK (1 test, 5 assertions)
Copy after login

We can view what we printed in the app.log file Log information.

2. Class file introduction

Calculator.php

<?php  
class Calculator  
{  
    public function sum($a, $b)  
    {  
        return $a + $b;  
    }  
}  
?>
Copy after login
Copy after login

Unit test class:

CalculatorTest.php

<?php
namespace App\tests;
require_once __DIR__ . &#39;/../vendor/autoload.php&#39;;
require "Calculator.php";
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase
{
    public function testSum()
    {
        $obj = new Calculator;
        $this->assertEquals(0, $obj->sum(0, 0));
    }
}
Copy after login

Command execution:

> ./vendor/bin/phpunit tests/CalculatorTest
Copy after login

Execution result:

PHPUnit 6.4.1 by Sebastian Bergmann and contributors.
F                                                                   1 / 1 (100%)
Time: 117 ms, Memory: 4.00MB
There was 1 failure:
Copy after login

If we deliberately write the assertion here wrong, $this->assertEquals(1, $obj->sum(0 , 0));

Look at the execution results:

PHPUnit 6.4.1 by Sebastian Bergmann and contributors.
F                                                                   1 / 1 (100%)
Time: 117 ms, Memory: 4.00MB
There was 1 failure:
1) App\tests\CalculatorTest::testSum
Failed asserting that 0 matches expected 1.
/Applications/XAMPP/xamppfiles/htdocs/web/framework/tests/CalculatorTest.php:22
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
Copy after login

will directly report the method error message and line number, which helps us quickly find the bug

3. Advanced Usage

Are you tired of adding "test" in front of each test method name? Are you struggling to write multiple test cases because only the parameters of the call are different? My favorite advanced feature, which I now recommend to you, is called the Frame Builder.

Calculator.php

<?php  
class Calculator  
{  
    public function sum($a, $b)  
    {  
        return $a + $b;  
    }  
}  
?>
Copy after login
Copy after login

Command line to start the test case, use the keyword --skeleton

> ./vendor/bin/phpunit --skeleton Calculator.php
Copy after login

Execution result:

PHPUnit 6.4.1 by Sebastian Bergmann and contributors.
Wrote test class skeleton for Calculator to CalculatorTest.php.
Copy after login

Isn’t it very simple? Because there is no test data, add test data here, and then re-execute the above command

<?php  
class Calculator  
{  
    /** 
     * @assert (0, 0) == 0 
     * @assert (0, 1) == 1 
     * @assert (1, 0) == 1 
     * @assert (1, 1) == 2 
     */  
    public function sum($a, $b)  
    {  
        return $a + $b;  
    }  
}  
?>
Copy after login

Every method in the original class is tested for the @assert annotation. These are converted into test code, like this

    /**
     * Generated from @assert (0, 0) == 0.
     */
    public function testSum() {
        $obj = new Calculator;
        $this->assertEquals(0, $obj->sum(0, 0));
    }
Copy after login

Execution results:

Copy after login

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of Basic use of PHP testing framework PHPUnit. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles