Phpunit,期待一个方法完全运行两次

class TestMe
{
    public function method() { }
}

测试:

class TestTest extends PHPUnit_Framework_TestCase
{
    public function testA()
    {
        $stub = $this->getMock ('TestMe');
        $stub->expects ($this->exactly(2))->method('method');
    }

    public function testB()
    {
        $stub = $this->getMock ('TestMe');
        $stub->expects ($this->exactly(2))->method('method');
        $stub->method();
    }

    public function testC()
    {
        $stub = $this->getMock ('TestMe');
        $stub->expects ($this->exactly(2))->method('method');
        $stub->method();
        $stub->method();
    }

    public function testD()
    {
        $stub = $this->getMock ('TestMe');
        $stub->expects ($this->exactly(2))->method('method');
        $stub->method();
        $stub->method();
        $stub->method();
    }
}

testA,testB,testC通过,testD失败,这很奇怪.
testA甚至没有调用方法,所以它应该失败 – 但它过去了,为什么?
testB调用方法ONCE,但是我们预计TWICE应该失败 – 但它过去了,为什么?
testC没问题,没问题
testD失败所以没关系,没问题

也许精确()并不完全符合我的预期.我使用最新的4.3.4 PHPunit.

解决方法:

尝试在getMock调用添加要模拟的方法名称.

为了获得预期的结果,我将测试类修改为:

class TestTest extends \PHPUnit_Framework_TestCase
{
    public function testA()
    {
        $stub = $this->getMock ('TestMe',array('method'));
        $stub->expects ($this->exactly(2))->method('method');
    }

    public function testB()
    {
        $stub = $this->getMock ('TestMe',array('method'));
        $stub->expects ($this->exactly(2))->method('method')->withAnyParameters();
        $stub->method();
    }

    public function testC()
    {
        $stub = $this->getMock ('TestMe',array('method'));
        $stub->expects ($this->exactly(2))->method('method')->withAnyParameters();
        $stub->method();
        $stub->method();
    }

    public function testD()
    {
        $stub = $this->getMock ('TestMe',array('method'));
        $stub->expects ($this->exactly(2))->method('method')->withAnyParameters();
        $stub->method();
        $stub->method();
        $stub->method();
    }
}

结果是:

PHPUnit 4.3.4 by Sebastian Bergmann.

There were 3 failures:

1) Acme\DemoBundle\Tests\TestTest::testA
Expectation Failed for method name is equal to <string:method> when invoked 2 time(s).
Method was expected to be called 2 times, actually called 0 times.

2) Acme\DemoBundle\Tests\TestTest::testB
Expectation Failed for method name is equal to <string:method> when invoked 2 time(s).
Method was expected to be called 2 times, actually called 1 times.

3) Acme\DemoBundle\Tests\TestTest::testD
TestMe::method() was not expected to be called more than 2 times.

希望这有帮助

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...