4

记录下 phpunit 的入门使用方法

 1 year ago
source link: https://nicksxs.me/2022/10/16/%E8%AE%B0%E5%BD%95%E4%B8%8B-phpunit-%E7%9A%84%E5%85%A5%E9%97%A8%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

记录下 phpunit 的入门使用方法

2022-10-16php 7 72 0 Comments

这周开始打算写个比较简单的php工具包,然后顺带学习使用下php的单元测试,通过phpunit还是比较方便的,首先就composer require phpunit/phpunit
安装下 phpunit, 前面包就是通过 composer init 创建,装完依赖后就可以把自动加载代码生成下 composer dump-autoload
目录结构差不多这样

.
├── composer.json
├── composer.lock
├── oldfile.txt
├── phpunit.xml
├── src
│   └── Rename.php
└── tests
    └── RenameTest.php

2 directories, 6 files

src/是源码,tests/是放的单测,比较重要的是phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="php-rename">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>

其中bootstrap就是需要把依赖包的自动加载入口配上,因为这个作为一个package,也会指出命名空间
然后就是testsuite的路径,源码中

<?php
namespace Nicksxs\PhpRename;

class Rename
{
    public static function renameSingleFile($file, $newFileName): bool
    {
        if(!is_file($file)) {
            echo "it's not a file";
            return false;
        }
        $fileInfo = pathinfo($file);
        return rename($file, $fileInfo["dirname"] . DIRECTORY_SEPARATOR . $newFileName . "." . $fileInfo["extension"]);
    }
}

就是一个简单的重命名
然后test代码是这样,

<?php

// require_once 'vendor/autoload.php';

use PHPUnit\Framework\TestCase;
use Nicksxs\PhpRename\Rename;
use function PHPUnit\Framework\assertEquals;

class RenameTest extends TestCase 
{
    public function setUp() :void
    {
        $myfile = fopen(__DIR__ . DIRECTORY_SEPARATOR . "oldfile.txt", "w") or die("Unable to open file!");
        $txt = "file test1\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    }
    public function testRename()
    {
        Rename::renameSingleFile(__DIR__ . DIRECTORY_SEPARATOR . "oldfile.txt", "newfile");
        assertEquals(is_file(__DIR__ . DIRECTORY_SEPARATOR . "newfile.txt"), true);
    }

    protected function tearDown(): void
    {
        unlink(__DIR__ . DIRECTORY_SEPARATOR . "newfile.txt");
    }
}

setUptearDown 就是初始化跟结束清理的,但是注意如果不指明 __DIR__ ,待会的目录就会在执行 vendor/bin/phpunit 下面,
或者也可以指定在一个 tmp/ 目录下
最后就可以通过vendor/bin/phpunit 来执行测试
执行结果

❯ vendor/bin/phpunit
PHPUnit 9.5.25 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:00.005, Memory: 6.00 MB

OK (1 test, 1 assertion)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK