PHPUnit 中的模拟 - 具有不同参数的同一方法的多个配置

2022-01-08 00:00:00 mocking php phpunit

可以这样配置PHPUnit mock吗?

Is it possible to configure PHPUnit mock in this way?

$context = $this->getMockBuilder('Context')
   ->getMock();

$context->expects($this->any())
   ->method('offsetGet')
   ->with('Matcher')
   ->will($this->returnValue(new Matcher()));

$context->expects($this->any())
   ->method('offsetGet')
   ->with('Logger')
   ->will($this->returnValue(new Logger()));

我使用 PHPUnit 3.5.10,当我请求 Matcher 时它失败了,因为它需要Logger"参数.就像第二个期望是重写第一个,但是当我转储模拟时,一切看起来都很好.

I use PHPUnit 3.5.10 and it fails when I ask for Matcher because it expects "Logger" argument. It is like the second expectation is rewriting the first one, but when I dump the mock, everything looks ok.

推荐答案

从 PHPUnit 3.6 开始,有 $this->returnValueMap() 可用于根据给定参数返回不同的值方法存根.

As of PHPUnit 3.6, there is $this->returnValueMap() which may be used to return different values depending on the given parameters to the method stub.

相关文章