PHPUnit如何测试一个特定的方法,特定的参数,特定的答案,超过一个调用


PHPUnit how to test a specific method with specific parameter with specific answer for more than one call

我已经尝试测试一个特定方法的多个参数,并通过相同的模拟获得不同参数的不同答案。

这是我到目前为止所做的:

$mock = $this->getMockBuilder('MyClass')->disableOriginalConstructor()->getMock();
$mock->expects($this->any())
            ->method('myMethod')
            ->with($this->equalTo('param1'))
            ->will($this->returnValue('test1'));
$mock->expects($this->any())
            ->method('myMethod')
            ->with($this->equalTo('param2'))
            ->will($this->returnValue('test2'));

当我调用$myClass->myMethod('param1')时,一切正常,我得到'test1'

然而,这里有一个问题:

当我调用$myClass->myMethod('param2')时,我得到一个错误

断言两个字符串相等失败。——预期+++实际@@ @@——"param1"+"param2"

我发现的一个解决方案是为每个调用创建一个新的模拟。

$mock1 = $this->getMockBuilder('MyClass')->disableOriginalConstructor()->getMock();        
$mock1->expects($this->any())
    ->method('myMethod')
    ->with($this->equalTo('param1'))
    ->will($this->returnValue('test1'));
$mock2 = $this->getMockBuilder('MyClass')->disableOriginalConstructor()->getMock();
$mock2->expects($this->any())
    ->method('myMethod')
    ->with($this->equalTo('param2'))
    ->will($this->returnValue('test2'));

我不知道为什么需要这个,也许我用错了。

所以问题仍然是:

如何用特定的方法模拟相同的类,用于不同的参数并获得不同的返回值?

您还可以稍微简化一下这些语句。如果您需要做的只是模拟函数,以便在传递'param1'时返回'test1',那么这应该可以工作:

$mock->method('myMethod')
    ->with('param1')
    ->willReturn('test1');
$mock->method('myMethod')
    ->with('param2')
    ->willReturn('test2');

如果它是关于一个被测试类的依赖,在被测试的方法中被调用两次那么它可以这样做

$mock = $this->getMockBuilder('MyClass')->disableOriginalConstructor()->getMock();
$mock->expects($this->at(0))
            ->method('myMethod')
            ->with($this->equalTo('param1'))
            ->will($this->returnValue('test1'));
$mock->expects($this->at(1))
            ->method('myMethod')
            ->with($this->equalTo('param2'))
            ->will($this->returnValue('test2'));

第一次必须用arg param1调用,然后用$mock->myMethod('param1')调用,返回test1,第二次用arg param2调用,返回test2