在phpunit中模拟PDO函数问题

时间:2017-11-15 09:59:25

标签: php unit-testing pdo

这是我的功能,我试图测试它是否抛出异常:

    public function myFunction(): bool
    {
        $dateInterval = new \DateTime();
        $dateInterval->sub(new \DateInterval('PT24H'));

        /** @var \PDOStatement $stmt */
        $stmt = $this->pdo->prepare('SELECT SUM(`values`) FROM `event_tracker` WHERE `identifier` = ? AND `mutated_at` >= ? AND `source` = ? AND `customer` = ?');
        $stmt->execute([$this->identifier, $dateInterval->getTimestamp(), $this->source, $this->customer]);
        $sum = $stmt->fetchColumn(0);
        if ($this->checkSourceType($this->source) && $sum >= $this->amountLimitCMS[$this->storeId] ){
            $this->exceptionMessage($this->amountLimitCMS[$this->countryIso], $dateInterval->format('H:i d-m-Y'), $this->source);
        }
        if (!$this->checkSourceType($this->source) && $sum >= $this->amountLimitMagento[$this->storeId] ){
            $this->exceptionMessage($this->amountLimitMagento[$this->storeId], $dateInterval->format('H:i d-m-Y'), $this->source);
        }

        return true;
    }

这是我的unitTest函数:

    public function testAmountCheckForCMS()
    {
        $query = [
            'store_id' => 13,
            'shipping_countryiso2' => 'DK',
            'amount' => 4000,
        ];

        $customer = '000003090';
        $source = 'fulfillment_prod';

        $container = new Container();
        $container['db'] = function ($container) {
            return $this->createMock(\PDO::class);
        };

        $dateInterval = new \DateTime();
        $dateInterval->sub(new \DateInterval('PT24H'));
        $ordersPerCustomer = new AmountPerCustomer($container, $customer, $query, $source);

        $fetchAllMock = $this
            ->getMockBuilder('PDOStatement')
            ->setMethods(['execute'])
            ->getMock();
        $fetchAllMock
            ->expects($this->once())->method('fetchColumn')
            ->will($this->returnValue($query['amount']));

        try {
            $ordersPerCustomer->assertPassedCriteria();
            $this->fail("Expected Exception has not been raised.");
        }catch (\Exception $error) {
            $this->assertEquals($error->getMessage(), "Total order amount event given parameters exceed sum {$query['amount']} since {$dateInterval->format('H:i d-m-Y')} from source {$source}");
        }
    }

正如您所看到的,在我想要测试的函数中,使用了executefetchColumn函数。我怎么能嘲笑他们?现在,当我运行我的测试时,我收到此错误消息:

Trying to configure method "fetchColumn" which cannot be configured because it does not exist, has not been specified, is final, or is static

任何想法我该如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:0)

我知道我来晚了,但是您需要在ockBuilder中设置该方法,以便可以对其进行模拟。

这是示例代码-

$this->getMockBuilder(PDOStatement::class)
        ->disableOriginalConstructor()
        ->setMethods(["fetchColumn"])
        ->getMock();