The PHPUnit manual highlights some conventions:
MyClass
go into a class MyClassTest
MyClassTest
live in file MyClassTest.php
MyClassTest
inherits from PHPUnit_Framework_TestCase
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.
And if using PHP > 5.3, namespaces can be used to allow class names to match:
There are reasons not to do this:
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
.
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