PHPUnit “Mocked method does not exist.” when using $mock->expects($this->at(…))

前端 未结 7 1460
失恋的感觉
失恋的感觉 2021-02-05 00:56

I\'ve run into a strange issue with PHPUnit mock objects. I have a method that should be called twice, so I\'m using the \"at\" matcher. This works for the first time the method

7条回答
  •  伪装坚强ぢ
    2021-02-05 01:32

    The issue ended up being with how I understood the "at" matcher to work. Also, my example was not verbatim how it is in my unit test. I thought the "at" matcher counter worked on a per query basis, where it really works on a per object instance basis.

    Example:

    class MyClass {
    
        public function exists($foo) {
            return false;
        }
    
        public function find($foo) {
            return $foo;
        }
    }
    

    Incorrect:

    class MyTest extends PHPUnit_Framework_TestCase
    {
    
        public function testThis()
        {
            $mock = $this->getMock('MyClass');
            $mock->expects($this->at(0))
                 ->method('exists')
                 ->with($this->equalTo('foo'))
                 ->will($this->returnValue(true));
    
            $mock->expects($this->at(0))
                 ->method('find')
                 ->with($this->equalTo('foo'))
                 ->will($this->returnValue('foo'));
    
            $mock->expects($this->at(1))
                 ->method('exists')
                 ->with($this->equalTo('bar'))
                 ->will($this->returnValue(false));
    
            $this->assertTrue($mock->exists("foo"));
            $this->assertEquals('foo', $mock->find('foo'));
            $this->assertFalse($mock->exists("bar"));
        }
    
    }
    

    Correct:

    class MyTest extends PHPUnit_Framework_TestCase
    {
    
        public function testThis()
        {
            $mock = $this->getMock('MyClass');
            $mock->expects($this->at(0))
                 ->method('exists')
                 ->with($this->equalTo('foo'))
                 ->will($this->returnValue(true));
    
            $mock->expects($this->at(1))
                 ->method('find')
                 ->with($this->equalTo('foo'))
                 ->will($this->returnValue('foo'));
    
            $mock->expects($this->at(2))
                 ->method('exists')
                 ->with($this->equalTo('bar'))
                 ->will($this->returnValue(false));
    
            $this->assertTrue($mock->exists("foo"));
            $this->assertEquals('foo', $mock->find('foo'));
            $this->assertFalse($mock->exists("bar"));
        }
    
    }
    

提交回复
热议问题