Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

phpunit

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?

like image 623
snakile Avatar asked Aug 23 '11 09:08

snakile


People also ask

What attribute will make a function to call only once for the entire test run?

This attribute is to identify methods that are called once prior to executing any of the tests in a fixture.

Is JUnit setup called for each test?

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 do I run a specific test in PHPUnit?

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.

Which method is used to create a mock with PHPUnit?

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.


2 Answers

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.

like image 121
borrible Avatar answered Sep 30 '22 06:09

borrible


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.

like image 24
Dane Powell Avatar answered Sep 30 '22 06:09

Dane Powell