你能否在PHPUnit中检查没有getMock的函数调用次数

时间:2012-05-09 21:22:00

标签: php phpunit

我的测试套件在对象A中调用accepted。然后,该函数将为对象B调用insert一定次数,具体取决于我正在运行的测试。

我想验证每个测试中insert被调用了适当的次数。我不我可以使用mock来计算它,因为对象A不会在我的测试中击中模拟。

我从2年前看到这个问题: PHPUnit Test How Many Times A Function Is Called

使用全局变量进行计数并不理想,因为我的类中不应该有专门用于类的代码。

修改

注意insert是静态的可能会有所帮助。即使我模拟了类并指定我只想模拟该函数,它仍然会在模拟对象上调用new,这是我面临的另一个障碍。

ANSWER 答案是不。我只是希望@zerkms给出答案,因为他是帮助我的人,所以我可以接受它。

我最终想到我只能使用一个对象,但确实遇到了另一个障碍: Why isn't PHPUnit counting this function as having ran?

2 个答案:

答案 0 :(得分:0)

在这种特殊情况下似乎是不可能的。

但在某些特定情况下,您可以模拟静态方法:http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

class Foo
{
    public static function doSomething()
    {
        return static::helper();
    }

    public static function helper()
    {
        return 'foo';
    }
}

试验:

public function testQQQ()
{
    $class = $this->getMockClass(
        'Foo',          /* name of class to mock     */
        array('helper') /* list of methods to mock   */
    );

    $class::staticExpects($this->exactly(2))
        ->method('helper')
        ->will($this->returnValue('bar'));

    $this->assertEquals(
        'bar',
        $class::doSomething()
    );
}

结果:

$ phpunit --filter QQQ
PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from /var/www/.../phpunit.xml

F

Time: 1 second, Memory: 10.75Mb

There was 1 failure:

1) ...::testQQQ
Expectation failed for method name is equal to <string:helper> when invoked 2 time(s).
Method was expected to be called 2 times, actually called 1 times.


FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

答案 1 :(得分:0)

您可以使用runkit动态重新定义静态方法(但您可能不应该这样做)。除此之外,您将不得不重组代码。使用非静态调用和依赖注入(因此对象A从外部源接收对象B,测试可以传递模拟)或使用依赖注入容器,以便类名未连接并且您的测试可以创建一个模拟子类,让类A使用它(这更麻烦,但是你的非测试代码需要更少的更改,因为你可以保持你的方法静态)。

相关问题