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

后端 未结 5 1910
无人共我
无人共我 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:40

    setUpBeforeClass() is the way to do this if all of your tests are literally contained within a single class.

    However, your question sort of implies that you may be using your test class as a base class for multiple test classes. In that case setUpBeforeClass will be run before each one. If you only want to run it once you could guard it with a static variable:

    abstract class TestBase extends TestCase {
    
      protected static $initialized = FALSE;
    
      public function setUp() {
        if (!self::$initialized) {
          // Do something once here for _all_ test subclasses.
          self::$initialized = TRUE;
        }
      }
    
    }
    

    A final option might be a test listener.

提交回复
热议问题