单元测试¶
概览¶
编写适当的测试可以帮助编写更好的软件。如果您设置了适当的测试用例,可以消除大多数功能性错误,并更好地维护您的软件。
将 PHPUnit 与 Phalcon 集成¶
或者通过手动将其添加到composer.json:
安装 PHPUnit 后,在项目根目录下创建一个名为tests的目录,并在其中创建一个名为Unit:
配置测试命名空间¶
为了自动加载我们的测试目录,我们需要将测试命名空间添加到 composer 中。将以下内容添加到 composer 并根据需要进行修改。
现在,创建一个phpunit.xml文件如下:
The phpunit.xml文件¶
 修改phpunit.xml以下内容以适应您的需求,并将其保存在项目根目录中。这将在tests/Unit目录下。
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         verbose="true"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuite name="Phalcon - Unit Test">
        <directory>./tests/Unit</directory>
    </testsuite>
</phpunit>
Phalcon 孵化器测试¶
Phalcon 提供了一个测试库,提供了一些您可以用来引导单元测试本身的抽象类。这些文件存在于Phalcon 孵化器测试仓库。
您可以通过将其作为依赖项添加来使用孵化器测试库:
或者通过手动将其添加到composer.json:
创建单元测试¶
建议始终使用命名空间自动加载您的类。下面的配置假设您正在使用 PSR-4 通过 composer 配置自动加载项目类。这样做的话,自动加载器将确保加载正确的文件,因此您只需要创建文件,phpunit 将为您运行测试。
此示例不包含配置文件,因为在大多数情况下您应该模拟您的依赖项。如果需要,您可以将其添加到DI中传递AbstractUnitTest.
抽象单元测试¶
首先,创建一个名为AbstractUnitTest.php中更改了tests/Unit目录:
<?php
declare(strict_types=1);
namespace Tests\Unit;
use Phalcon\Di\Di;
use Phalcon\Di\FactoryDefault;
use Phalcon\Incubator\Test\PHPUnit\UnitTestCase;
use PHPUnit\Framework\IncompleteTestError;
abstract class AbstractUnitTest extends UnitTestCase
{
    private bool $loaded = false;
    protected function setUp(): void
    {
        parent::setUp();
        $di = new FactoryDefault();
        Di::reset();
        Di::setDefault($di);
        $this->loaded = true;
    }
    public function __destruct()
    {
        if (!$this->loaded) {
            throw new IncompleteTestError(
                "Please run parent::setUp()."
            );
        }
    }
}
您的第一个测试¶
创建以下测试并将其保存在您的tests/Unit目录下。
<?php
declare(strict_types=1);
namespace Tests\Unit;
class UnitTest extends AbstractUnitTest
{
    public function testTestCase(): void
    {
        $this->assertEquals(
            "roman",
            "roman",
            "This will pass"
        );
        $this->assertEquals(
            "hope",
            "ava",
            "This will fail"
        );
    }
}
如果需要重载setUp方法,请务必调用父方法,否则 Phalcon 将无法正确初始化。
    protected function setUp(): void
    {
        parent::setUp();
        //...
    }
````
### Running Unit Tests
When you execute `vendor/bin/phpunit` in your command line, you will get the following output:
```bash
$ phpunit
PHPUnit 9.5.23 by Sebastian Bergmann and contributors.
Runtime:       PHP 8.1.8 with Xdebug 3.1.5
Configuration: /var/www//phpunit.xml
Time: 3 ms, Memory: 3.25Mb
There was 1 failure:
1) Test\Unit\UnitTest::testTestCase
This will fail
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'hope'
+'ava'
/var/www/tests/Unit/UnitTest.php:25
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.