关于模拟PDO类的问题

时间:2019-04-14 15:05:26

标签: mocking phpunit

在setUp()函数中,我想使用PDOMock类,其定义如下

namespace TddProject;
class PDOMock extends \PDO
{
  public function __construct() {}
}

但是当我运行测试时,出现此错误:

Argument 1 passed to TddProject\InvoiceManager::__construct() must be an instance of PDO, instance of Mock_PDOMock_7d3c9396 given, called in /Applications/MAMP/htdocs/tdd_project/tests/InvoiceManagerTest.php on line 35 and defined
/Applications/MAMP/htdocs/tdd_project/src/InvoiceManager.php:16

InvoiceManager类具有以下构造函数:

public function __construct(\PDO $db)
{
    $this->db = $db;
}

似乎看不到PDOMock。您能建议我如何解决这个问题吗? 谢谢


编辑:

这是完整的测试课程:

<?php


use TddProject\Customer;
use TddProject\Invoice;
use TddProject\InvoiceManager;

class InvoiceManagerTest extends PHPUnit_Framework_TestCase
{

    private $stmMock;
    private $pdoMock;

    public function setUp()
    {
        $this->stmMock = $this->getMock('PDOStatement', array('execute','fetch'));
        $this->stmMock->expects($this->any())->method('execute')
            ->will($this->returnValue(true));

        $this->pdoMock = $this->getMock('PDOMock', array('prepare','lastInsertId'));
        $this->pdoMock->expects($this->any())->method('prepare')
            ->will($this->returnValue($this->stmMock));
    }


    public function testRaiseInvoice() {
        $this->pdoMock->expects($this->once())
            ->method('lastInsertId')->will($this->returnValue(1));

        $invoiceManager = new InvoiceManager($this->pdoMock);

        $product1 = new \TddProject\Product();
        $product1->price = 10;
        $product1->product_id = 1;

        $customer = new Customer();
        $customer->customer_id = 1;

        $invoice = new Invoice();
        $productsArray = array(array(
            'product' => $product1,
            'quantity' => 2
            ));

        $invoiceManager->raiseInvoice($invoice, $customer, $productsArray);

        $this->assertEquals(20, $invoice->price_total);
    }

}

1 个答案:

答案 0 :(得分:0)

我通过删除InvoiceManager构造函数声明中的参数类型解决了该问题。