2013-04-07 73 views
0

我想比較一個對象作爲「與」的參數給我的模擬對象。 當我比較var_dump預期和實際他們看起來相當。 我的預感是我在->with參數中做錯了。 由於事先phpunit:比較Mock對象與()的對象參數

我的測試代碼

public function testAddEntry() 
{ 
    $expected = new Entry(); 
    var_dump($expected); 
    $dbRef = $this->getMock('EntriesDAO'); 
    $dbRef->expects($this->once())->method('insert') 
     ->with($expected); 
    $actual = EntryHelper::addEntry($dbRef, $req); 

功能代碼從控制檯

測試

static function addEntry($iDao, $req) 
{ 
$actual = new Entry(); 
var_dump($actual); 
$actual->newId = $iDao->insert($actual); 

輸出

class Entry#212 (4) { 
    public $id => 
    NULL 
    public $content => 
    string(0) "" 
    public $date => 
    string(0) "" 
    public $userId => 
    NULL 
} 
class Entry#209 (4) { 
    public $id => 
    NULL 
    public $content => 
    string(0) "" 
    public $date => 
    string(0) "" 
    public $userId => 
    NULL 
} 

Time: 0 seconds, Memory: 2.75Mb 

There was 1 failure: 

1) EntryHelperTest::testAddEntry 
Expectation failed for method name is equal to <string:insert> when invoked 1 time(s). 
Parameter 0 for invocation EntriesDAO::insert(Entry Object (...)) does not match expected value. 
Failed asserting that two objects are equal. 

回答

1

也許,PHPUnit的使用the identity operator (===)檢查對象是平等的。如在手冊

所述...用恆等算子(===)時,對象變量是相同的,當且僅當它們指的是同一類

的相同實例。由於您在方法addEntry()中創建Entry的新實例,則比較將失敗。

+0

我在想這也可能是問題,但後來我能夠爲不同的方法編寫測試..「update」工作。我找到了差異和根本原因。我將返回值分配給對象。 $ actual-> newId = $ iDao-> insert($ actual);這一定是修改比較值。 – 2013-04-07 15:26:24

0

根本原因。我將返回值分配給對象。 在我測試的功能,

$actual->newId = $iDao->insert($actual); 

而這必須被修改的比較值。 我固定它通過分離分配給

$newId = $iDao->insert($actual); 

*注意,修改$測試仍然調用模擬休息後實際。所以這是行不通的。

$actual->id = $newId;