PHPUnit 测试套件命名约定


PHPUnit test suite naming conventions

PHPUnit 手册重点介绍了一些约定:

  • 班级的测试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批注,以便方法名称可以匹配。

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

有理由不这样做:

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

    use MyProject'MyClass as MyActualClass;
    

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

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