模拟会影响您的断言计数吗?

jon*_*tyc 6 phpunit

我注意到当我使用模拟对象时,PHPUnit将正确报告执行的测试数量但错误地报告我正在进行的断言数量.事实上,每次我嘲笑它都算作另一个断言.一个包含6个测试的测试文件,7个断言语句和每个测试模拟一次报告6个测试,13个断言.

这是除了一个测试以外的所有测试的测试文件(这里用于说明),另外我介绍了另一个不存根以追踪此问题的测试.PHPUnit报告了2个测试,3个断言.我删除了dummy:1 test,2个断言.

require_once '..\src\AntProxy.php';

class AntProxyTest extends PHPUnit_Framework_TestCase {
    const sample_client_id = '495d179b94879240799f69e9fc868234';    
    const timezone = 'Australia/Sydney';
    const stubbed_ant = "stubbed ant";
    const date_format = "Y";

    public function testBlankCategoryIfNoCacheExists() {
        $cat = '';
        $cache_filename = $cat.'.xml';
        if (file_exists($cache_filename))
            unlink($cache_filename);

        $stub = $this->stub_Freshant($cat);

        $expected_output = self::stubbed_ant;
        $actual_output = $stub->getant();
        $this->assertEquals($expected_output, $actual_output);
    }

    public function testDummyWithoutStubbing() {
        $nostub = new AntProxy(self::sample_client_id, '', self::timezone, self::date_format);
        $this->assertTrue(true);
    }    

    private function stub_FreshAnt($cat) {
        $stub = $this->getMockBuilder('AntProxy')
                     ->setMethods(array('getFreshAnt'))
                     ->setConstructorArgs(array(self::sample_client_id, $cat, self::timezone, self::date_format))
                     ->getMock();

        $stub->expects($this->any())
             ->method('getFreshAnt')
             ->will($this->returnValue(self::stubbed_ant));

        return $stub;
    }
}
Run Code Online (Sandbox Code Playgroud)

这就像一个断言留在框架的一个模拟方法中.有没有办法显示每个(传递)断言?

Dav*_*ess 9

每个测试方法完成后,PHPUnit将验证测试期间的模拟期望设置.PHPUnit_Framework_TestCase::verifyMockObjects()增加创建的每个模拟对象的断言数.如果您真的想通过存储当前断言数,调用父方法并减去差异,可以覆盖撤消此方法.

protected function verifyMockObjects()
{
    $count = $this->getNumAssertions();
    parent::verifyMockObjects();
    $this->addToAssertionCount($count - $this->getNumAssertions());
}
Run Code Online (Sandbox Code Playgroud)

当然,verifyMockObjects()如果任何期望不满意,将抛出断言失败异常,因此您需要捕获异常并在重置计数后重新抛出它.我会留给你的.:)

  • 当您使用模拟作为测试的一部分时,这是有意义的:“调用 X 将导致它在模拟上调用 Y。如果没有,测试就会被破坏。” 但是,当您使用模拟作为存根来使测试更容易时,这只是噪音:“调用 X 将需要调用 Y,但它只需要 `false`,所以返回它。” 最后,我不会将断言的数量用于任何事情,所以这并不重要。 (2认同)