我正在尝试在 PHPUnit 测试中模拟 Predis 客户端。当我调用我试图模拟的方法时,在测试结束时 PHPUnit 告诉我没有达到预期。
这是重现我的问题的代码示例:
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");
}
并且 PHPUnit 认为该方法没有被调用:
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.
为什么?是不是因为 Predis 客户端好像在使用 __call 来响应匹配 redis 命令的方法调用?
更新:我的印象是它与 __call 方法有关。将代码更改为此有效:
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");
}
但不确定我对此是否满意。有没有更好的方法来模拟使用 __call 代理方法的类?
最佳答案
我觉得你可以用
$mockRedis = $this->getMock('Predis\\Client', array('exists'));
// ...
强制模拟对象知道你的魔法函数。这限制了 mock 对方法 exists()
的能力。您必须特别包含要模拟的所有其他方法。
关于php - 为什么我的 Predis 客户端的 PHPUnit 模拟不符合我的预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807368/