6

记录下 phpunit 的入门使用方法之setUp和tearDown

 1 year ago
source link: https://nicksxs.me/2022/10/23/%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%E4%B9%8BsetUp%E5%92%8CtearDown/
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 的入门使用方法之setUp和tearDown

2022-10-23php 3 66 0 Comments

可能是太久没写单测了,写个单测发现不符合预期,后来验证下才反应过来
我们来看下demo

class RenameTest extends TestCase
{
    public function setUp(): void
    {
        var_dump("setUp");
    }

    public function test1()
    {
        var_dump("test1");
        assertEquals(1, 1);
    }

    public function test2()
    {
        var_dump("test2");
        assertEquals(1, 1);
    }

    protected function tearDown(): void
    {
        var_dump("tearDown");
    }
}

因为我是想写个重命名的小工具,希望通过setUptearDown做一些文件初始化和清理工作,但是我把两个case的初始化跟清理工作写到了单个setUptearDown中,这样就出现了异常的错误
通过上面的示例代码,可以看到执行结果

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

.string(5) "setUp"
string(5) "test1"
string(8) "tearDown"
.                                                                  2 / 2 (100%)string(5) "setUp"
string(5) "test2"
string(8) "tearDown"


Time: 00:00.005, Memory: 6.00 MB

OK (2 tests, 2 assertions)

其实就是很简单的会在每个test方法前后都执行setUptearDown

Buy me a coffee

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK