Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit test suite naming conventions

The PHPUnit manual highlights some conventions:

  • The tests for a class MyClass go into a class MyClassTest
  • The class MyClassTest live in file MyClassTest.php
  • MyClassTest inherits from PHPUnit_Framework_TestCase
  • Tests are public methods that are named test*

This will result in something like this folder structure:

├── src/
│   ├── classes/
│   │   ├── MyClass.php # Different
│   └── ...
├── tests/
│   ├── testcases/
│   │   ├── MyClassTest.php # Different
│   ├── bootstrap.php
│   └── ...
└── ...

... and this test case:

MyClassTest extends PHPUnit_Framework_TestCase {

    testMyMethod() {
        // Code here.
    }
}

My question

I'm wondering if there is any reason why the naming used inside the test suite can't mirror the project's source code? For example, I'm thinking file names could match:

├── src/
│   ├── classes/
│   │   ├── MyClass.php # Same
│   └── ...
├── tests/
│   ├── testcases/
│   │   ├── MyClass.php # Same
│   ├── bootstrap.php
│   └── ...
└── ...

And if using PHP > 5.3, namespaces can be used to allow class names to match:

namespace MyProject\MyTests;

MyClass extends PHPUnit_Framework_TestCase { # The class name MyClass matches the class name used in my project's source.

    /**
     * @test
     */
    MyMethod() {  # The method name MyMethod matches the method name used in my project's source. 
        // Code here.
    }
}

Note the @tests annotation is used so method names can match.

like image 540
henrywright Avatar asked Feb 12 '16 22:02

henrywright


1 Answers

And if using PHP > 5.3, namespaces can be used to allow class names to match:

There are reasons not to do this:

  • It makes sense to have test and class under test in the same namespace
  • Otherwise you need to import the class under test with a class alias to distinguish it from the test case:

    use MyProject\MyClass as MyActualClass;
    

The method name MyMethod matches the method name used in my project's source.

This might sound appealing if you think of testMyMethod as the alternative, but this is not the convention. Instead you should use more descriptive test method names like testThatMyMethodReturnsTrueIfFooIsBar.

like image 133
Fabian Schmengler Avatar answered Oct 09 '22 22:10

Fabian Schmengler