Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: how to test that methods are called in incorrect order?

I want to use PHPUnit to test that methods are called in the right order.

My first attempt, using ->at() on a mock object, did not work. For example, I expected the following to fail, but it does not:

  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();
  }      

The only way I could think of that forced a failure if things were called in the wrong order was something like this:

  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();
  }

Is there a more elegant way to do this? Thanks!

like image 698
des4maisons Avatar asked Mar 29 '13 23:03

des4maisons


1 Answers

You need involve any InvocationMocker to make your expectations work. For example this should work:

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();
}  
like image 65
Cyprian Avatar answered Oct 21 '22 12:10

Cyprian