【问题标题】:PHPUnit -setUp() - does it run before and after each test case?PHPUnit -setUp() - 它在每个测试用例之前和之后运行吗?
【发布时间】:2016-01-07 04:35:01
【问题描述】:

我还是对 PHPUnit 中的setup() 有点困惑。

它是否在之前之后 每个测试用例运行?

例如,我想在每次测试之前清理我的文章表,但我想保留我已经注入表中的测试数据。因为我只想在下次测试之前清理它。

我的测试,

namespace Test\Foo\Article;

use Test\SuiteTest;
use Foo\Article;

class ArticleTest extends SuiteTest
{
    protected static $Article;

    /**
     * Call this template method before each test method is run.
     */
    protected function setUp()
    {
        $this->truncateTables(
            [
                'article'
            ]
        );

        self::$Article = new Article(self::$PDO);
    }

    public function testFetchRow()
    {
        self::$Article->createRow(
            [
                ':title' => 'Hello World',
                ':description' => 'Hello World',
                ':content' => 'Hello World'
            ]
        );

        $result = self::$Article->fetchRow(
            [
                ':article_id' => self::$PDO->fetchLastInsertId()
            ]
        );

        $this->assertArrayHasKey('article_id', $result);

        $expected = 12; // 12 keys associate with values in the array
        $this->assertEquals($expected, count($result));
    }
}

我查看了我的文章表,没有没有测试数据了,看来setup()已经清理过了。它应该如何工作?

tearDown() 怎么样 - 是否意味着 每个 测试用例之后运行?

【问题讨论】:

    标签: phpunit php-5.6


    【解决方案1】:

    setUp() 在每个测试方法之前运行,tearDown() 在每个测试方法之后运行。

    PHPUnit 手册 - 第 4 章修复:

    在运行测试方法之前,调用名为 setUp() 的模板方法

    ...

    一旦测试方法完成运行,无论成功还是失败,都会调用另一个名为 tearDown() 的模板方法

    https://phpunit.de/manual/current/en/fixtures.html

    【讨论】:

    • 谢谢,不过改成public之后就没什么区别了。
    • method signiature 受到保护
    • 不,setUp() 可以被保护。
    猜你喜欢
    • 2014-05-02
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2019-07-19
    • 2017-02-11
    • 1970-01-01
    相关资源
    最近更新 更多