Codeception \ Util \ Stub方法:: exact和:: once不起作用

问题描述 投票:10回答:2

我正在使用Codeception \ Util \ Stub来创建单元测试。我想确保我的方法多次调用。为此,我正在使用'确切'的方法。

例:

use \UnitTester;
use \Codeception\Util\Stub as StubUtil;

class someCest
{
    public function testMyTest(UnitTester $I)
    {
        $stub = StubUtil::makeEmpty('myClass', [
            'myMethod' => StubUtil::exactly(2, function () { return 'returnValue'; })
        ]);
        $stub->myMethod();
    }
}

如你所见,我给myMethod打过一次电话。但测试通过了。与method :: once相同的问题,因为此方法使用相同的类PHPUnit_Framework_MockObject_Matcher_InvokedCount(下面的'matcher')。只有当我打电话超过预期时间(> 2)时,测试才会失败。因为matcher的方法'invoked'检查计数是否超出预期。但是看不出是否有人调用matcher的方法'verify'来检查myMethod是否调用的次数少于预期。

抱歉stackoverflow,这是我的第一个问题。

UPDATE

我的快速和BAD临时解决方案:

将存根添加到帮助器中

$I->addStubToVerify($stub);

将方法添加到帮助程序以验证:

protected $stubsToVerify = [];
public function verifyStubs()
{
    foreach ($this->stubsToVerify as $stub) {
        $stub->__phpunit_getInvocationMocker()->verify();
    }
    return $this;
}

在Cest的方法_after()中调用此方法:

public function _after(UnitTester $I)
{
    $I->verifyStubs();
}
php unit-testing stub codeception
2个回答
6
投票

你需要将$this作为第三个参数传递给makeEmpty

$stub = StubUtil::makeEmpty('myClass', [
    'myMethod' => StubUtil::exactly(2, function () { return 'returnValue'; })
], $this);

0
投票

而不是使用\Codeception\Util\StubExpected::once(),将你的单元测试修改为extends \Codeception\Test\Unit然后使用$this->make()$this->makeEmpty()来创建你的存根。它会像你期望的那样工作;)

例如:

class MyProcessorTest extends \Codeception\Test\Unit 
{
    public function testSomething()
    {
        $processor = new MyProcessor(
            $this->makeEmpty(EntityManagerInterface::class, [
                'remove' => Expected::never(),
                'persist' => Expected::once(),
                'flush' => Expected::once(),
            ])
        );

        $something = $this->somethingFactory(Processor::OPERATION_CREATE);
        $processor->process($something);
    }
}

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.