PHPUnit: How do I create a function to be called once for all the tests in a class?

后端 未结 5 1911
无人共我
无人共我 2021-02-02 04:58

I have a PHPUnit test case class (consisting of some test functions). I would like to write a oneTimeSetUp() function to be called once for all my tests in the clas

5条回答
  •  孤街浪徒
    2021-02-02 05:38

    Expanding on accepted answer:

    None of the setUpBeforeClass(), tearDownAfterClass(), @beforeClass, @afterClass runs in the object context (static methods). You can work around that restriction by guarding any @before code with a static property instead, like so:

    class MyTest extends PHPUnit\Framework\TestCase
    {
        private static $ready = false;
    
        /**
         * @before
         */
        protected function firstSetUp()
        {
            if (static::$ready))
                return;
    
            /* your one time setUp here */
    
            static::$ready = true;
        }
    }
    

    It can't be used for @after, however, because there's no way of saying when the last test was called.

提交回复
热议问题