2014-10-31 25 views
2
class TestMe 
{ 
    public function method() { } 
} 

測試:PHPUnit的,期望的方法恰好運行兩次

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(); 
    } 
} 

種皮,TESTB,TESTC流逝,僅TESTD失敗,這是奇數。 testA甚至沒有調用方法,所以它應該失敗 - 但它通過了,爲什麼? testB調用方法ONCE,但我們預計TWICE應該失敗 - 但它通過了,爲什麼? testC是好的,沒問題 testD因此無法正常工作,沒問題

也許正好()並不能完全符合我的預期。我使用最新的4.3.4 PhPunit。

回答

4

嘗試在getMock調用中添加想要模擬的方法名稱。

爲了獲得aspected結果我修改測試類爲:

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. 

希望這有助於