如何完全控制MockObject的行为?

时间:2019-08-15 13:27:28

标签: phpunit phpunit-testing

我需要创建一个两倍的PHPUnit测试:

  • 使用某些方法的原始实现
  • 将其他方法替代了原始实现,但让我窥视了它们
  • 使用具有固定返回值的NOP存根替换其他方法,并且调用原始实现

我该怎么办?

->getMockBuilder()->getMock()->createMock()->createPartialMock()->createTestProxy()->getMockBuilder()->enableProxyingToOriginalMethods()->setProxyTarget()之间,我似乎能够满足上述三个要求中的两个,但不是全部三个。

1 个答案:

答案 0 :(得分:1)

通过模拟链接解决:

    protected function getMixedMock(
        string $className,
        array $constructorArgs,
        array $stubMethods,
        array $proxyMethods
    ) : array
    {
        $stub = $this->getMockBuilder($className)
            ->setMethods($stubMethods)
            ->getMock();

        $proxy = $this->getMockBuilder(Local::class)
            ->setConstructorArgs($constructorArgs)
            ->setMethods(array_unique(array_merge($stubMethods, $proxyMethods)))
            ->enableProxyingToOriginalMethods()
            ->setProxyTarget($stub)             // <-- CHAINING HERE
            ->getMock();

        return [$stub, $proxy];
    }

    public function test()
    {
        [$stub, $proxy] = $this->getMixedMock(
            LocalFSAdapter::class,
            ["/"],
            ['write'],
            ['has']
        );
        //methods that must be stubbed should be spied on using $stub
        //methods that must be proxied should be spied on using $proxy
        //use $proxy for testing
    }