PHPUnit 测试套件命名约定
PHPUnit test suite naming conventions
PHPUnit manual 强调了一些约定:
- class
MyClass
的测试进入 class MyClassTest
- class
MyClassTest
活在文件 MyClassTest.php
MyClassTest
继承自 PHPUnit_Framework_TestCase
- 测试是名为
test*
的 public 方法
这将导致类似这样的文件夹结构:
├── src/
│ ├── classes/
│ │ ├── MyClass.php # Different
│ └── ...
├── tests/
│ ├── testcases/
│ │ ├── MyClassTest.php # Different
│ ├── bootstrap.php
│ └── ...
└── ...
... 这个测试用例:
MyClassTest extends PHPUnit_Framework_TestCase {
testMyMethod() {
// Code here.
}
}
我的问题
我想知道是否有任何原因导致测试套件中使用的命名不能反映项目的源代码?例如,我认为文件名可以匹配:
├── src/
│ ├── classes/
│ │ ├── MyClass.php # Same
│ └── ...
├── tests/
│ ├── testcases/
│ │ ├── MyClass.php # Same
│ ├── bootstrap.php
│ └── ...
└── ...
如果使用 PHP > 5.3,命名空间可用于允许 class 名称匹配:
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.
}
}
请注意,使用了 @tests
注释以便方法名称可以匹配。
And if using PHP > 5.3, namespaces can be used to allow class names to match:
有理由不这样做:
- 在同一个命名空间中进行测试和 class 测试是有意义的
否则需要导入被测的class,加上class别名,以区别于测试用例:
use MyProject\MyClass as MyActualClass;
The method name MyMethod matches the method name used in my project's source.
如果您将 testMyMethod
视为备选方案,这听起来可能很吸引人,但这 不是 惯例。相反,您应该使用更具描述性的测试方法名称,例如 testThatMyMethodReturnsTrueIfFooIsBar
.
PHPUnit manual 强调了一些约定:
- class
MyClass
的测试进入 classMyClassTest
- class
MyClassTest
活在文件MyClassTest.php
MyClassTest
继承自PHPUnit_Framework_TestCase
- 测试是名为
test*
的 public 方法
这将导致类似这样的文件夹结构:
├── src/
│ ├── classes/
│ │ ├── MyClass.php # Different
│ └── ...
├── tests/
│ ├── testcases/
│ │ ├── MyClassTest.php # Different
│ ├── bootstrap.php
│ └── ...
└── ...
... 这个测试用例:
MyClassTest extends PHPUnit_Framework_TestCase {
testMyMethod() {
// Code here.
}
}
我的问题
我想知道是否有任何原因导致测试套件中使用的命名不能反映项目的源代码?例如,我认为文件名可以匹配:
├── src/
│ ├── classes/
│ │ ├── MyClass.php # Same
│ └── ...
├── tests/
│ ├── testcases/
│ │ ├── MyClass.php # Same
│ ├── bootstrap.php
│ └── ...
└── ...
如果使用 PHP > 5.3,命名空间可用于允许 class 名称匹配:
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.
}
}
请注意,使用了 @tests
注释以便方法名称可以匹配。
And if using PHP > 5.3, namespaces can be used to allow class names to match:
有理由不这样做:
- 在同一个命名空间中进行测试和 class 测试是有意义的
否则需要导入被测的class,加上class别名,以区别于测试用例:
use MyProject\MyClass as MyActualClass;
The method name MyMethod matches the method name used in my project's source.
如果您将 testMyMethod
视为备选方案,这听起来可能很吸引人,但这 不是 惯例。相反,您应该使用更具描述性的测试方法名称,例如 testThatMyMethodReturnsTrueIfFooIsBar
.