Why isn't my PHPUnit mock of the Predis Client matching my expectations?
Asked Answered
C

3

5

I'm trying to mock out the Predis client in a PHPUnit test. When I call the method I've tried to mock out, at the end of the test PHPUnit is telling me that the expectation was not met.

Here's a code sample that reproduces my problem:

class MockRedisTest extends \PHPUnit_Framework_TestCase {
private $mockRedis;

public function testMockRedis() {

    $mockRedis =  $this->getMock('Predis\\Client');

    $mockRedis->expects(  $this->once())
      ->method("exists")
      ->with($this->equalTo("query-key"))
      ->will($this->returnValue(true));

    $mockRedis->exists("query-key");
}

}

And PHPUnit thinks the method wasn't called:

1) MockRedisTest::testMockRedis Expectation failed for method name is equal to when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times.

Why? Is it because the Predis client appears to be using __call to respond to method calls that match redis commands?

UPDATE: I get the impression it has something to do with the __call method. Changing the code to this works:

public function testMockRedis() {

    $mockRedis =  $this->getMock('Predis\\Client');

    $mockRedis->expects(  $this->once())
      ->method("__call")
      ->with("exists", $this->equalTo(array("query-key")))
      ->will($this->returnValue(true));

    $mockRedis->exists("query-key");
}

Not sure I'm satisfied with this though. Is there a better way to mock classes that use __call to proxy methods?

Clod answered 18/10, 2011 at 12:41 Comment(0)
H
8

I think you can use

$mockRedis =  $this->getMock('Predis\\Client', array('exists'));
// ...

to force the mock object to know about your magic function. This limits to mock's capabilities to the method exists() though. You'll have to specifically include every other method to be mocked.

Hemisphere answered 18/10, 2011 at 13:26 Comment(0)
K
1

For Phpunit 5, use

$this->createPartialMock('Predis\\Client', ['exists']);

To make your mock know about the "exists" method (or any other redis native command)

Kela answered 8/11, 2016 at 9:23 Comment(0)
K
0

If you want to mock a specific server profile and make sure you are not calling methods of a different server version, use

<?php
$mockRedis = $this->getMock('Predis\\Client', array_keys((new Predis\Profiles\ServerVersion26)->getSupportedCommands()));
Kirkkirkcaldy answered 2/8, 2012 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.