PHPUnit测试套件命名约定

PHPUnit测试套件命名约定,php,unit-testing,phpunit,Php,Unit Testing,Phpunit,报告强调了一些公约: 类MyClass的测试进入类MyClassTest 类MyClassTestlive-in文件MyClassTest.php MyClassTest继承自PHPUnit\u框架\u测试用例 测试是名为test* 这将导致类似以下文件夹结构的结果: ├── src/ │ ├── classes/ │ │ ├── MyClass.php # Different │ └── ... ├── tests/ │ ├── testcases/ │ │ ├

报告强调了一些公约:

  • MyClass
    的测试进入类
    MyClassTest
  • MyClassTest
    live-in文件
    MyClassTest.php
  • MyClassTest
    继承自
    PHPUnit\u框架\u测试用例
  • 测试是名为
    test*
这将导致类似以下文件夹结构的结果:

├── src/
│   ├── classes/
│   │   ├── MyClass.php # Different
│   └── ...
├── tests/
│   ├── testcases/
│   │   ├── MyClassTest.php # Different
│   ├── bootstrap.php
│   └── ...
└── ...
。。。这个测试用例:

MyClassTest extends PHPUnit_Framework_TestCase {

    testMyMethod() {
        // Code here.
    }
}
use MyProject\MyClass as MyActualClass;
我的问题

我想知道为什么测试套件中使用的命名不能反映项目的源代码?例如,我认为文件名可以匹配:

├── 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,则可以使用名称空间来允许类名匹配:

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.
    }
}
有理由不这样做:

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

    MyClassTest extends PHPUnit_Framework_TestCase {
    
        testMyMethod() {
            // Code here.
        }
    }
    
    use MyProject\MyClass as MyActualClass;
    
方法名MyMethod与项目源中使用的方法名匹配


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

,原因在于惯例。与类名称的大小写相同。没有什么能阻止您按照自己的意愿命名测试类。对于其他开发人员来说,这可能看起来很奇怪,结果会是一个相反的问题——为什么不遵循约定呢?谢谢你提供的信息。我也在想同样的事情,但是让我的测试完全反映我的来源对我来说是有意义的。我的意思是,如果你能给一种测试方法和被测试方法取相同的名字,为什么要给它们取不同的名字呢?这是一个稍微不同的反问句。其中一个约定是公开预期结果,例如,关于第二点(使用方法名称,如
testThatMyMethodReturnsTrueIfFooIsBar
),是因为每个测试方法可能有多个测试方法?例如
testThatMyMethodReturnsTrueIfFooIsBar
testthatMyMethodDoesMethingElse
Yes,通常情况下,您将有一个测试方法用于“快乐路径”,一个或多个测试方法用于预期错误