【问题标题】:Issue about mocking PDO class关于模拟 PDO 类的问题
【发布时间】:2019-09-04 16:47:14
【问题描述】:

在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);
    }

}

【问题讨论】:

  • 如何在测试中实例化 InvoiceManager 类?
  • @Sachem 你好,我刚刚添加了关于测试类的代码

标签: mocking phpunit


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    相关资源
    最近更新 更多