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 class (unlike the standard setUp()
function which is called once for each test in the class). In other words, I'm looking for a PHPUnit equivalent to the JUnit @BeforeClass
annotation.
Same question with a oneTimeTearDown()
function.
Is it possible to do so in PHPUnit?
This attribute is to identify methods that are called once prior to executing any of the tests in a fixture.
First, JUnit 4 has a setup method that is invoked before each test method. This method is typically used for creating and configuring the system under test. This means that: We should create the dependencies of the tested object in this method.
How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.
PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With