0

Would anybody, please, show me an example for at method in phpunit test doubles. I don't understand what is its purpose?

akond
  • 14,891
  • 4
  • 32
  • 54
jjoselon
  • 2,053
  • 2
  • 15
  • 31

1 Answers1

3

The purpose of the at() function is to specify the order that methods on a mock should be called. If you were to use once() or exactly(), the test would pass no matter which order the methods were called as PHPUnit is only checking that they are called during the test not when.

For example:

class FooTest extends PHPUnitTestCase {
    public function testProperOrderOfMethods() {
         $mockObject = $this->getMockBuilder('BarObject')
             ->setMethods(['baz', 'boz'])
             ->getMock();

         $mockObject->expects($this->at(0))
             ->method('boz');

         $mockObject->expects($this->at(1))
             ->method('bar');

         $sut = new Foo();
         $sut->methodBeingTested($mockObject);
}

This requires that our function needs to look like:

public function methodBeingTested($dependecy) {
    $dependency->boz();
    $dependency->bar();
}

And would fail if the function order were changed.

An example use case might be your class is using an object that connects to a service and retrieves data. You would want to have the connection opened, retrieve the data, and then close the connection. Or it may need to make further requests depending on the response. Either way all of these actions need to happen in a specific order so in your test, you would use at().

Schleis
  • 34,455
  • 6
  • 60
  • 79