在一个应用程序中设置PHPUnit的方法指南

176 阅读1分钟

在这个例子中,我们将在一个假的应用程序中设置PHPUnit并运行测试。

项目结构

project
|-- src
|---- Application
|------ Service
|-------- TwitterService.php
|-- tests
|---- Application
|------ Service
|-------- TwitterServiceTest.php
|-- vendor
|---- ...
|-- composer.lock
|-- composer.json
|-- phpunit.xml

安装

运行$ composer require phpunit/phpunit --dev 来安装 phpunit 包。

设置

在项目根目录下将以下文件保存为phpunit.xml :

<?xml version="1.0" encoding="UTF-8"?>
<phpunit
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.1/phpunit.xsd"
        backupGlobals="false"
        colors="true"
        bootstrap="vendor/autoload.php">

    <testsuites>
        <testsuite name="ApplicationSuite">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory>
        </whitelist>
    </filter>
</phpunit>

你的测试套件名称是ApplicationSuite ,你需要把你的测试文件放在项目根目录下的tests

使用方法

假设我们有下面的测试类:

namespace tests\Application\Service;

use PHPUnit\Framework\TestCase;

class TwitterServiceTest extends TestCase
{
    public function testSetMessage()
    {
    }
    
    public function testGetMessage()
    {
    }
}

运行所有的测试:

$ vendor/bin/phpunit

按套件名称运行所有测试:

$ vendor/bin/phpunit --configuration phpunit.xml --testsuite ApplicationSuite

在一个特定的文件夹中运行所有的测试:

$ vendor/bin/phpunit tests/Application/Service

运行单个测试类中的单个测试方法。**注意:**如果有另一个测试方法的名字以testSetMessage 开始,PHPUnit也会运行它。例如:testSetMessageAnother

$ vendor/bin/phpunit --filter testSetMessage TwitterServiceTest tests/Application/Service/TwitterServiceTest.php

运行单个测试类中的所有测试方法:

$ vendor/bin/phpunit --filter TwitterServiceTest tests/Application/Service/TwitterServiceTest.php