dongshanxun6479
2013-01-17 09:46
浏览 43
已采纳

模拟对象并保留其他方法的功能

Say for example I have this class:

class Foo {

    public function add($x, $y)
    {
        return $x + $y;
    }

    public function subtract($x, $y)
    {
        return $x - $y;
    }
}

and I wanted to change the behavior of the add method only:

$mock = $this->getMock('Foo');
$mock->expects($this->once())->method('add')->will($this->returnCallback(function ($x, $y) {
    return ($x + 0) + ($y + 0);
}));

$this->assertEquals(4, $mock->add(2,2));
$this->assertEquals(2, $mock->subtract(4,2));

Why is my subtract method now returning null? I was expecting it to behave usual.

Failed asserting that null matches expected 2.

图片转代码服务由CSDN问答提供 功能建议

比如说我有这个类:

  class Foo  {
 
公共函数add($ x,$ y)
 {
返回$ x + $ y; 
} 
 
公共函数减法($ x,$ y)
 {
返回 $ x  -  $ y; 
} 
} 
   
 
 

我只想更改add方法的行为:

  $ mock = $ this-> getMock('Foo'); 
 $ mock-> expect($ this-> once()) - > method('add') - &gt  ; will($ this-> returnCallback(function($ x,$ y){
 return($ x + 0)+($ y + 0); 
})); 
 
 $ this-&gt  ; assertEquals(4,$ mock-> add(2,2)); 
 $ this-> assertEquals(2,$ mock-> subtract(4,2)); 
   
 
 

为什么我的减法方法现在返回null? 我原以为它表现得很平常。

 声明null与预期匹配失败2. 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanguanzai6181 2013-01-17 10:04
    已采纳

    Use like this:

    $mock = m::mock('Foo[add]');
    
    已采纳该答案
    打赏 评论
  • dongzhina7098 2013-01-17 10:03

    You need to do a partial mock specifying to getMock what method you want to mock:

    $mock = $this->getMock('Foo', array('add');
    

    In this way only the add method is mocked, the rest of the object is behaving as usual.

    打赏 评论

相关推荐 更多相似问题