PHPUnit:当使用不同参数多次调用相同的存根方法时,在测试中忽略期望订单

时间:2015-01-19 08:51:30

标签: mocking phpunit expectations

我有一个方法(让我们称之为method2),它调用另一个方法(让我们称之为method1)多次但使用不同的参数。

这是类,MyClass.php:

<?php

class MyClass
{

    public function method1($arg)
    {
        return 'arg was ' . $arg;
    }

    public function method2()
    {
        // Calling the first time with 'one'
        $this->method1('one');

        // Calling other functions
        // ...

        // Calling the first time with 'two'
        $this->method1('two');
    }
}

测试时,我为method1创建一个存根,以便控制调用它的方式/时间和返回的内容。在我对method2的测试中,我遵循在method2中执行代码的顺序。

这是测试类,MyClassTest.php:

<?php

require_once 'MyClass.php';

class MyClassTest extends PHPUnit_Framework_TestCase
{

    /** @test */
    public function method2_was_called_successfully_with_one_and_then_two()
    {
        $myClassMock = $this->getMockBuilder('MyClass')
                            ->setMethods(['method1'])
                            ->getMock();

        $myClassMock->expects($this->once())
                    ->method('method1')
                    ->with($this->stringContains('one', true))
                    ->will($this->returnValue('arg was one'));

        // Testing code for the code between the two calls
        // ...

        $myClassMock->expects($this->once())
                    ->method('method1')
                    ->with($this->stringContains('two', true))
                    ->will($this->returnValue('arg was two'));

        $myClassMock->method2();
    }
}

在我的测试中,看起来PHPUnit不遵循这个顺序并且遇到方法1的最后一个(在本例中为第二个)调用:

  

有1次失败:

     

1)MyClassTest :: method2_was_called_successfully_with_one_and_then_two   方法名称的期望失败等于何时   调用1次(s)参数0用于调用MyClass :: method1('one')   与预期值不符。声明'one'包含的失败   “二”。

     

/path/to/the/files/MyClass.php:14   /path/to/the/files/MyClassTest.php:28

     

FAILURES!测试:1,断言:0,失败:1。

关于我遗失/做错的基本事情是什么?

1 个答案:

答案 0 :(得分:2)

配置模拟时,您必须使用at()而不是once()

    $myClassMock = $this->getMockBuilder('MyClass')
                        ->setMethods(['method1'])
                        ->getMock();

    $myClassMock->expects($this->at(0))
                ->method('method1')
                ->with($this->stringContains('one', true))
                ->will($this->returnValue('arg was one'));

    $myClassMock->expects($this->at(1))
                ->method('method1')
                ->with($this->stringContains('two', true))
                ->will($this->returnValue('arg was two'));


    // Testing code
    // ....
    // ....

另外,在我执行了一些测试代码后,配置模拟对我来说很奇怪。通常的模式是配置模拟在测试开始时应该接收的所有调用。然后运行SUT并检查是否已完成所有呼叫(通常最后一步是自动的)。

相关问题