search
HomeBackend DevelopmentPHP TutorialHow to use PHP unit testing framework PHPUnit
How to use PHP unit testing framework PHPUnitOct 25, 2017 pm 02:38 PM
phpphpunitInstructions

When I was learning IOS development, I wrote an article specifically about unit testing in Objective-C. Unit testing for learning IOS development. Today I will summarize how to use unit testing in PHP.

1. Preface

In this article, we use the dependency package management tool of composer to install and manage phpunit packages , the official address of composer 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 coomposer.json configuration file in the root directory and enter the following content:

{
    "autoload": {
        "classmap": [
            "./"
        ]
    }
}

The above means that all classes in the root directory will be Files are loaded in. After executing composer install on the command line, a vendor folder will be generated in the root directory. We will use composer in the future. Any third-party code installed 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 and is a popular PHP framework today. They 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 to install PHPUnit. For other installation methods, please see here

composer require --dev phpunit/phpunit ^6.2

Install the Monolog log package and make phpunit test records For logging.

composer require monolog/monolog

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"
    },

4. Simple usage of PHPUnit

1. Single file test

Create directorytests, create a new fileStackTest.php, edit 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;
    }
}

Code explanation:

  1. StackTest is the test class

  2. StackTest inherits from PHPUnit\Framework\TestCase

  3. Test methodtestPushAndPop(), the test method must have public permissions, usually starting with test, or you can choose to give it Add comment @test to indicate

  4. In the test method, an assertion method similar to assertEquals() is used to compare the actual value with An assertion is made on a match of expected values.

Command line execution:
phpunit command test file naming

➜  framework#  ./vendor/bin/phpunit tests/StackTest.php

// 或者可以省略文件后缀名
//  ./vendor/bin/phpunit tests/StackTest

Execution result:

➜  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)

We can View the log information we printed in the app.log file.

2. Class file introduction

Calculator.php

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

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));

    }

}

Command execution:

> ./vendor/bin/phpunit tests/CalculatorTest

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:

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.

will directly report the method error message and line number, which will help 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 the parameters you call are different? My favorite advanced feature, which I now recommend to you, is called Framework Generator.

Calculator.php

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

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

> ./vendor/bin/phpunit --skeleton Calculator.php

Execution result:

PHPUnit 6.4.1 by Sebastian Bergmann and contributors.

Wrote test class skeleton for Calculator to CalculatorTest.php.

Isn’t it very simple, because there is no test data, so 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;  
    }  
}  
?>

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

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

Execution results:


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

Statement
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
PHP开发中如何使用PHPUnit进行Mock测试PHP开发中如何使用PHPUnit进行Mock测试Jun 27, 2023 am 10:25 AM

在PHP开发中,测试是非常重要的一个环节,测试可以大大减少错误的发生,提高代码质量。Mock测试是测试中的一种形式,它可以模拟出虚假的对象或数据,以便测试我们代码的某个特定功能或场景。PHPUnit是PHP中非常流行的一个测试框架,它支持Mock测试。在这篇文章中,我们将探讨如何使用PHPUnit进行Mock测试。一、什么是Mock测试在开始之前,我们先来了

PHP中的测试报告工具PHP中的测试报告工具May 24, 2023 am 08:24 AM

PHP是一种常见的开源编程语言,广泛应用于Web开发中,它的优点就在于易学、易用、可拓展性强等优点。而作为开发者,我们为了在保证代码质量的同时提高开发效率,必不可少的就是测试和测试报告的使用。在PHP开发中,有很多测试和测试报告工具,其中最常见的就是PHPUnit。然而,PHPUnit虽然简单易用,但是需要一些编写测试用例的基础知识,如果不熟悉,使用起来还是

php如何使用PHPUnit和Mockery进行单元测试?php如何使用PHPUnit和Mockery进行单元测试?May 31, 2023 pm 04:10 PM

在PHP项目开发中,单元测试是一项很重要的任务。PHPUnit和Mockery是两个相当流行的PHP单元测试框架,其中PHPUnit是一个被广泛使用的单元测试工具,而Mockery则是一个专注于提供统一而简洁的API以创建和管理对象Mock的对象模拟工具。通过使用PHPUnit和Mockery,开发人员可以快速高效地进行单元测试,以确保代码库的正确性和稳定性

PHP中的代码检查工具PHP中的代码检查工具May 24, 2023 pm 12:01 PM

检查代码质量是每个程序员都必须要做的任务,而PHP中也有很多工具可以用于检查代码的质量和风格,从而提高代码的可读性和可维护性,提高代码的可靠性和安全性。本文将介绍几种常见的PHP代码检查工具,并对它们进行简单的比较和评估,希望可以帮助读者在开发过程中选择合适的工具,提高代码质量和效率。PHP_CodeSnifferPHP_CodeSniffer是一个广泛应用

如何使用PHP和PHPUnit检查代码规范和质量如何使用PHP和PHPUnit检查代码规范和质量Jun 25, 2023 pm 04:57 PM

在现代的软件开发中,代码质量和规范是极为重要的因素。不仅可以让代码更加整洁易于维护,还可以提高代码的可读性和可扩展性。但是,如何检查代码的质量和规范呢?本文将介绍如何使用PHP和PHPUnit来实现这一目标。第一步:检查代码规范在PHP开发中,有一种非常流行的代码规范,它被称为PSR(PHP标准规范)。PSR规范的目的是使PHP代码更具可读性和可维护性。其中

PHP编程中有哪些常见的代码质量工具?PHP编程中有哪些常见的代码质量工具?Jun 12, 2023 am 08:16 AM

PHP编程中有哪些常见的代码质量工具?在现代的软件开发中,代码质量是非常重要的。如果代码质量不好,不仅会降低代码的可读性,增加维护难度,还会造成安全漏洞等一系列问题。而在PHP编程中,我们可以使用一些代码质量工具来检查代码的质量。本文将介绍一些常见的PHP代码质量工具。PHP_CodeSnifferPHP_CodeSniffer是一个用于静态分析PHP代码的

如何使用PHPUnit进行PHP单元测试如何使用PHPUnit进行PHP单元测试May 12, 2023 am 08:13 AM

随着软件开发行业的发展,测试逐渐成为了不可或缺的一部分。而单元测试作为软件测试中最基础的一环,不仅能够提高代码质量,还能够加快开发者开发和维护代码的速度。在PHP领域,PHPUnit是一个非常流行的单元测试框架,它提供了各种功能来帮助我们编写高质量的测试用例。在本文中,我们将介绍如何使用PHPUnit进行PHP单元测试。安装PHPUnit在使用PHPUnit

如何在Go中使用命令行参数?如何在Go中使用命令行参数?May 10, 2023 pm 07:03 PM

在Go语言中,命令行参数是非常重要的一种方式,用于向程序传递输入并指定运行时的行为。Go提供了一个标准库flag来解析命令行参数,本文将介绍如何在Go中使用命令行参数。什么是命令行参数命令行参数是在程序运行时通过命令行传递给程序的参数,用于指定程序运行时的行为和输入。举个例子,Linux中的ls命令可以接受多个命令行参数,如-l用于列出详细信息,-a用于显示

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.