为什么它需要一个模拟抽象类构造函数的参数

时间:2017-09-18 21:07:54

标签: unit-testing mocking phpunit stub

我正在尝试模仿AbstractQuery类的教义

    $this->abstractQuery = $this->getMockForAbstractClass('Doctrine\ORM\AbstractQuery')
                                ->disableOriginalConstructor();

现在我要做我的存根

    $this->abstractQuery->expects($this->at(1))
                        ->method('getResult')
                        ->willReturn('our query result');

我收到此错误

Argument 1 passed to Doctrine\ORM\AbstractQuery::__construct() must be an instance of Doctrine\ORM\EntityManagerInterface, none given

disabledOriginalConstructor phpunit的方法默认为false

/...
public function disableOriginalConstructor()
{
    $this->originalConstructor = false;

    return $this;
}
/...
它采用了

getMockForAbstractClass方法

public function getMockForAbstractClass()
{
    $object = $this->generator->getMockForAbstractClass(
        $this->type,
        $this->constructorArgs,
        $this->mockClassName,
        $this->originalConstructor,
        $this->originalClone,
        $this->autoload,
        $this->methods,
        $this->cloneArguments
    );

    $this->testCase->registerMockObject($object);

    return $object;
}

任何想法?

1 个答案:

答案 0 :(得分:2)

disableOriginalConstructor()MockBuilder类的API,而不是$this->getMockForAbstractClass('Doctrine\ORM\AbstractQuery')

的类

有两种选择。

1)首先:

仍在使用方法getMockForAbstractClass

$this->abstractQuery = $this->getMockForAbstractClass(
    'Doctrine\ORM\AbstractQuery', 
    [], // default value
    '', // default value
    false, // this is $callOriginalConstructor argument
    true, // default value
    true, // default value
    ['getResult'] // here we define methods that we want to mock
);

2)第二:

使用MockBuilder

$this->abstractQuery = $this
    ->getMockBuilder('Doctrine\ORM\AbstractQuery')
    ->setMethods(['getResult'])
    ->disableOriginalConstructor()
    ->getMockForAbstractClass();

我个人更喜欢MockBuilder,因为它更具可读性。