可以使用$這裏面回調以獲取PHPUnit中嘲笑類的保護性能? 或者有其他方法可以實現嗎?
$mock = $this->getMock('A', array('foo'));
$mock->expects($this->any())->method('foo')->will(
$this->returnCallback(function() {
return $this->bar;
}));
這可能是非常有用的,如果你考慮注入模擬對象。 有時類有其他類的硬編碼的依賴,但它與方法,理論上你可以嘲笑和戲弄創建對象,而不是硬編碼的對象創建它。請看另一個例子。
class A {
protected $bar = "bar";
public function foo() {
$b = new B();
return $b->fizz($this->bar);
}
}
class B {
public function fizz ($buzz) {
return $buzz;
}
}
但讓我們說B類做的不好,我想用模擬來代替它。
$mockB = $this->getMock('B');
// (...) - and probably mock other things
$mockA = $this->getMock('A', array('foo'));
$mockA->expects($this->any())->method('foo')->will(
$this->returnCallback(function() use ($mockB) {
return $mockB->fizz($this->bar);
}));
這是否可以實現?
當然沒有任何驚喜,目前,如果我這樣做像上面然後我得到錯誤:
PHP Fatal error: Using $this when not in object context in (...)
使用use
關鍵字我可以從父作用域繼承$ mockA:
$mockB = $this->getMock('B');
// (...) - and probably mock other things
$mockA = $this->getMock('A', array('foo'));
$mockA->expects($this->any())->method('foo')->will(
$this->returnCallback(function() use ($mockA, $mockB) {
return $mockB->fizz($mockA->bar);
}));
但這樣我會嘗試訪問酒吧作爲公衆,我會得到:
PHP Fatal error: Cannot access protected property (...)
是的,我知道我可以定義公共的getter但可以說這是一個外部庫,或者你只是想保持它的保護。整個問題是關於如何在特定情況下獲得類的受保護屬性。所以對於PHP 5.3來說,答案仍然是否定的,你不能那樣做。對於PHP 5.4,你可以使用$ this!這是一個巨大的進步!但仍然需要改變我不想改變的課程。你至少可以創建擴展A的類來添加'getCallback(B $ b)'?需要檢查。 – 2013-02-10 12:59:52