2013-03-29 5 views
7

Voglio utilizzare PHPUnit per verificare che i metodi siano chiamati nell'ordine corretto.PHPUnit: come verificare che i metodi vengano chiamati in ordine errato?

Il mio primo tentativo, utilizzando ->at() su un oggetto fittizio, non ha funzionato. Per esempio, mi aspettavo il seguente a fallire, ma non è così:

public function test_at_constraint() 
    { 
    $x = $this->getMock('FirstSecond', array('first', 'second')); 
    $x->expects($this->at(0))->method('first'); 
    $x->expects($this->at(1))->method('second'); 

    $x->second(); 
    $x->first(); 
    }  

L'unico modo che ho potuto pensare che costretto un fallimento se le cose sono stati chiamati in ordine errato era qualcosa di simile:

public function test_at_constraint_with_exception() 
    { 
    $x = $this->getMock('FirstSecond', array('first', 'second')); 

    $x->expects($this->at(0))->method('first'); 
    $x->expects($this->at(1))->method('first') 
     ->will($this->throwException(new Exception("called at wrong index"))); 

    $x->expects($this->at(1))->method('second'); 
    $x->expects($this->at(0))->method('second') 
     ->will($this->throwException(new Exception("called at wrong index"))); 

    $x->second(); 
    $x->first(); 
    } 

C'è un modo più elegante per farlo? Grazie!

+0

Guarda http://api.drupal.org/api/drupal/core%21vendor%21phpunit%21phpunit-mock-objects%21PHPUnit%21Framework%21MockObject%21Matcher%21InvokedAtIndex. php/function/PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex% 3A% 3Averify/8 – jcbwlkr

+0

Penso che aiuterà ma non ne sono sicuro. – jcbwlkr

+0

Quella pagina sembra indicare che '-> at()' non causerà un errore se il suo metodo è chiamato a un indice diverso, che il mio primo caso di test dimostra già. C'era qualcos'altro che avevi in ​​mente da quella pagina che sarebbe stato utile? – des4maisons

risposta

7

È necessario coinvolgere qualsiasi InvocationMocker per far funzionare le proprie aspettative. Per esempio, questo dovrebbe funzionare:

public function test_at_constraint() 
{ 
    $x = $this->getMock('FirstSecond', array('first', 'second')); 
    $x->expects($this->at(0))->method('first')->with(); 
    $x->expects($this->at(1))->method('second')->with(); 

    $x->second(); 
    $x->first(); 
} 
+0

A parte il fatto che fallisce con "il metodo Mocked non esiste" nella mia versione di phpunit, funziona! ECCEZIONALE! – des4maisons

Problemi correlati