如何使用PHPUnit测试调用同一类的其他方法但不返回任何值的方法

Pet*_*ete 5 php testing phpunit unit-testing codeception

如何为调用同一类的其他方法但不返回值的方法编写单元测试?(让我们说PHPUnit.)

例如,假设我有以下类:

class MyClass {

    public function doEverything() {

        $this->doA;
        $this->doB;
        $this->doC;

    }

    public function doA() {
        // do something, return nothing
    }

    public function doB() {
        // do something, return nothing
    }

    public function doC() {
        // do something, return nothing
    }

}
Run Code Online (Sandbox Code Playgroud)

你会怎么测试doEverything()

编辑:

我问这个是因为从我看过的内容看来,几乎所有的方法都应该有自己的专用单元测试.当然,你也有功能和集成测试,但那些目标特定的例程,可以这么说(不是必须在每个方法级别).

但是,如果几乎所有方法都需要自己的单元测试,我认为对所有上述方法进行单元测试将是"最佳实践".是/否?

Pet*_*ete 8

好的!我已经明白了!正如所料,嘲讽是什么,我需要在这种情况下-和嘲讽兄弟姐妹方法被称为部分嘲讽.在Juan Treminio的这篇文章中有关于PHPUnit 模拟的一些非常好的信息.

所以要doEverything()在上面的课上测试,我需要做这样的事情:

public function testDoEverything()
{

    // Any methods not specified in setMethods will execute perfectly normally,
    // and any methods that ARE specified return null (or whatever you specify)
    $mock = $this->getMockBuilder('\MyClass')
        ->setMethods(array('doA', 'doB', 'doC'))
        ->getMock();

    // doA() should be called once
    $mock->expects($this->once())
         ->method('doA');

    // doB() should be called once
    $mock->expects($this->once())
         ->method('doB');

    // doC() should be called once
    $mock->expects($this->once())
         ->method('doC');

    // Call doEverything and see if it calls the functions like our
    // above written expectations specify
    $mock->doEverything();
}
Run Code Online (Sandbox Code Playgroud)

而已!满容易!

奖励:如果你使用Laravel和Codeception ......

我正在使用Laravel框架以及Codeception,这使得弄清楚它有点棘手.如果你使用Laravel和Codeception,你需要做更多的工作,因为Laravel自动加载不会默认连接到PHPUnit测试.你基本上需要更新你的unit.suite.ymlLaravel4,如下所示:

# Codeception Test Suite Configuration

# suite for unit (internal) tests.
class_name: UnitTester
modules:
    enabled: [Asserts, UnitHelper, Laravel4]
Run Code Online (Sandbox Code Playgroud)

更新文件后,请不要忘记致电php codecept.phar build更新配置.