PHPUnit -setUp() - does it run before and after each test case?

laukok picture laukok · Oct 9, 2015 · Viewed 15.7k times · Source

I am still a bit confused with setup() in PHPUnit.

Does it run before and after each test case?

For intance, I want to clean up my article table before each test but I want to keep the test data that I already injected into the table. Because I only want to clean it until the next test.

My test,

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));
    }
}

I check my article table, there is no test data anymore, it seems that setup() has cleaned it up. Is it how it should work?

What about the tearDown() - does it mean to run after the each test case?

Answer

StoryTeller picture StoryTeller · Oct 9, 2015

setUp() runs before every single test method, tearDown() runs after each test method.

PHPUnit Manual - Chapter 4 Fixures:

Before a test method is run, a template method called setUp() is invoked

...

Once the test method has finished running, whether it succeeded or failed, another template method called tearDown() is invoked

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