PHPUnit测试套件命名约定

hen*_*ght 5 php phpunit unit-testing

PHPUnit的手动亮点一些约定:

  • 一堂课的考试MyClass进入一堂课MyClassTest
  • 班级MyClassTest直播文件MyClassTest.php
  • MyClassTest 继承自 PHPUnit_Framework_TestCase
  • 测试是名为的公共方法 test*

这将导致类似于以下文件夹结构:

??? src/
?   ??? classes/
?   ?   ??? MyClass.php # Different
?   ??? ...
??? tests/
?   ??? testcases/
?   ?   ??? MyClassTest.php # Different
?   ??? bootstrap.php
?   ??? ...
??? ...
Run Code Online (Sandbox Code Playgroud)

...以及这个测试案例:

MyClassTest extends PHPUnit_Framework_TestCase {

    testMyMethod() {
        // Code here.
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题

我想知道是否有任何原因导致测试套件中使用的命名无法反映项目的源代码?例如,我认为文件名可以匹配:

??? src/
?   ??? classes/
?   ?   ??? MyClass.php # Same
?   ??? ...
??? tests/
?   ??? testcases/
?   ?   ??? MyClass.php # Same
?   ??? bootstrap.php
?   ??? ...
??? ...
Run Code Online (Sandbox Code Playgroud)

如果使用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.
    }
}
Run Code Online (Sandbox Code Playgroud)

注意,@tests使用了注释,以便方法名称可以匹配。

Fab*_*ler 4

如果使用 PHP > 5.3,则可以使用命名空间来允许类名匹配:

不这样做的原因如下:

  • 将测试和测试类放在同一名称空间中是有意义的
  • 否则,您需要使用类别名导入被测试的类,以将其与测试用例区分开来:

    use MyProject\MyClass as MyActualClass;
    
    Run Code Online (Sandbox Code Playgroud)

方法名称 MyMethod 与我的项目源中使用的方法名称相匹配。

如果您认为这testMyMethod是替代方案,这可能听起来很有吸引力,但这不是惯例。相反,您应该使用更具描述性的测试方法名称,例如testThatMyMethodReturnsTrueIfFooIsBar.

  • 关于你的第二点(使用像“testThatMyMethodReturnsTrueIfFooIsBar”这样的方法名称),是因为你可能为每个被测试的方法有多个测试方法吗?例如 `testThatMyMethodReturnsTrueIfFooIsBar` 和 `testThatMyMethodDoesSomethingElse` (2认同)