18

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?

laukok
  • 47,545
  • 146
  • 388
  • 689

1 Answers1

25

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

Sven
  • 62,889
  • 9
  • 98
  • 100
StoryTeller
  • 1,433
  • 11
  • 25
  • 1
    thanks but it has no difference at all after changing that to `public`. – laukok Oct 09 '15 at 15:37
  • the [method signiature](https://github.com/sebastianbergmann/phpunit/blob/90dc6817d2268aa861da1a90a93678b9452c2e71/src/Framework/TestCase.php#L1938) is protected – jack Oct 11 '15 at 14:04
  • 3
    No, `setUp()` can be protected. – Sven Oct 16 '15 at 21:52