- Quick start
$stub = $this->getMockBuilder('modelAbc') ->setMethods(array('findFirst')) ->getMock(); $stub->expects($this->any()) ->method('findFirst') ->will($this->returnValue(null));
- 靜態寫法 (PHPUnit 3.9後就不支援static寫法了)
$stub = $this->getMockClass( 'modelAbc', array('findHistory') ) ; $stub::staticExpects($this->any()) ->method('findHistory') ->will($this->returnValue($result));
method執行次數
Example:$stub->expects($this->once()) ->method('doSomething'); $this->once(); 只會被執行一次 $this->exactly(3); //只能3次 $this->any(); //不管幾次
method 回傳值
- 回傳固定值
語法:$this->returnValue()
Example:
$stub->expects($this->any()) ->method('doSomething') ->will($this->returnValue("Yes, sir!");
- 隨機回傳不同值
語法:
- 依參數給回傳不同值
語法:$this->returnValueMap(array(param1, ..., paramN, returnValue)
Example:
$stub->expects($this->any()) ->method('doSomething') ->will( $this->returnValueMap( array( array('a', 'b', 'c', 'd'), array('e', 'f', 'g', 'h')) ) ) ); $this->assertEquals('d', $stub->doSomething('a', 'b', 'c')); $this->assertEquals('h', $stub->doSomething('e', 'f', 'g'));
Issue
- Phalcon\Mvc\Model\Exception: The method "__phpunit_getInvocationMocker" doesn't exist on model
- Solution
一般因為有namespace,只要補上完整的namespace即可
$stub = $this->getMockBuilder('namespace_path\modelAbc');
- Solution
Reference
沒有留言:
張貼留言