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

Take a look at setUpBeforeClass() from section 6 of the PHPUnit documentation.

For the one time tearDown you should use tearDownAfterClass();.

Both this methods should be defined in your class as static methods.


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() {
    
    parent::setUp();

    if (!self::$initialized) {
      // Do something once here for _all_ test subclasses.
      self::$initialized = TRUE;
    }
  }

}

A final option might be a test listener.