Home » Php » php – Testing levels/groups in PHPUnit

php – Testing levels/groups in PHPUnit

Posted by: admin July 12, 2020 Leave a comment


We already have some PHPUnit tests implemented on our codebase. However, moving forward, in the interest of minimizing the time required to run tests, I’d like to separate out our tests into two groups, or levels:

  1. Tests that are very low-level and don’t hit the test database (unit tests)
  2. Tests that are higher level and interact with the test database (sometimes called component or integration tests)

This would allow us to just run the level 1 test when working on basic functionality, while running both level 1 and 2 when working on higher-level functionality, or before committing to the main line/build.

How would I go about accomplishing this with PHPUnit?

How to&Answers:

@Schleis’ answer is entirely correct and very useful. The only catch (which I admittedly didn’t include in my question) is that I’d like to be able to scatter Unit and Integration tests throughout our test files – I want to avoid having two files of tests – one file for Unit tests for SomeClass, and a separate file for Functional tests, also for SomeClass.

The PHPUnit command-line option that I found that enables this is groups:

Only runs tests from the specified group(s). A test can be tagged as belonging to a group using the @group annotation.

To use this approach, you simply add the @group annotation to the multiline comment before your tests as such:

class SomeClassTest extends PHPUnit_Framework_TestCase {
     * @group Unit
    public function testSomeUnitFunctionality() {
        $this->assertEquals(xyz(' .a1#2 3f4!', true), ' 12 34');

     * @group Integration
    public function testSomeIntegrationFunctionality() {
        $this->assertEquals(xyz(' .a1#2 3f4!', true), ' 12 34');

This allows me to do the following:

  • phpunit --group Unit (Just unit tests)
  • phpunit --group Integration (Just integration tests)
  • phpunit (All tests)


You can write a phpunit.xml that will seperate your tests into test suites that you can run separately.


It would look similar to:

    <testsuite name="Unit_Tests">
    <testsuite name="Functional_Tests">

Then when you want to run only one group of tests you would call phpunit --testsuite Unit_Tests or phpunit --testsuite Functional_Tests as needed.