【发布时间】:2016-05-24 06:05:26
【问题描述】:
PHPUnit manual 强调了一些约定:
-
MyClass类的测试进入MyClassTest类 - 班级
MyClassTest存在于文件MyClassTest.php -
MyClassTest继承自PHPUnit_Framework_TestCase - 测试是名为
test*的公共方法
这将导致类似这样的文件夹结构:
├── 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,可以使用命名空间来允许类名匹配:
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注解,所以方法名可以匹配。
【问题讨论】:
-
原因是约定。与例如相同类名的驼峰式。没有什么能阻止您按照自己的意愿命名测试类。对于其他开发人员来说,这可能看起来很奇怪,并且会产生相反的问题——为什么不遵循约定。
-
感谢您的信息。我也在想同样的事情,但让我的测试完全反映我的来源的吸引力对我来说很有意义。我的意思是,如果可以将测试方法和被测方法命名相同,为什么要对它们进行不同的命名?
-
这是一个略有不同的反问。 convention 之一是公开预期结果,例如
testMyMethodDoesTheStuff()
标签: php unit-testing phpunit