unit-testing - PHPUnit 模拟方法调用了 0 次,而它应该被调用一次

标签 unit-testing phpunit

我是单元测试的新手,在理解 phpunit 中的模拟对象时遇到问题。 我有以下功能:

public function createPaymentStatement()
{
    $tModel = new \FspInvoice\Model\Transaction();
    $paymentsArr = $this->transactionGateway->getTransactionWithStatus($tModel::SETTLED);
    $result = false;
    if(is_array($paymentsArr)){
            //some code here
            $result = $psArr;

    }

    return $result;
}

现在对上面的函数进行单测试:

 public function testCreatePaymentStatementWithPaymentsSettledReturnsArray()
{
    $this->transactionGateway = $this->getMockBuilder('FspInvoice\Model\TransactionsTable')
        ->setMethods(array('getTransactionWithStatus'))
        ->disableOriginalConstructor()
        ->getMock();
    $this->transactionGateway->expects($this->once())
        ->method('getTransactionWithStatus')
        ->will($this->returnValue(array(0,1,2)));
    $test = $this->service->createPaymentStatement();
    $this->assertTrue(is_array($test));
}

但是当我运行代码时出现错误:

   1)FspInvoiceTest\ServiceTest\PaymentTest::testCreatePaymentStatementWithPaymentsSettledReturnsArray
Expectation failed for method name is equal to <string:getTransactionWithStatus> when    invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

我做错了什么?

最佳答案

您的模拟从未传递给您正在测试的对象。你应该记住的是你不是模拟一个类,而是模拟一个类的对象。所以,你已经创建了一个模拟,然后你必须以某种方式将它传递给你的测试对象。在大多数情况下,您可以通过依赖注入(inject)来完成。

在您的原始类中注入(inject)依赖项(例如通过构造函数):

class TestedClass
{
    public function __construct(TransactionGateway $transactionGateway)
    {
        $this->transactionGateway = $transactionGateway;
    }

    public function createPaymentStatement()
    {
        // (...)
    }
}

然后在你的测试中:

// create a mock as you did
$transactionGatewayMock = (...)

// pass the mock into tested object
$service = new TestedClass($transactionGateway);

// run test
$this->assertSomething($service->createPaymentStatement());

关于unit-testing - PHPUnit 模拟方法调用了 0 次,而它应该被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21428327/

相关文章:

java - 测试是否对返回 Void 的方法内的变量调用了方法

java - 在单元测试中测试私有(private)组件

php - 静态方法中使用的模拟方法

selenium - 对刚刚执行了 type() 的元素进行 verifyText() 有意义吗?

PHPUnit:数据库测试的多个数据集

unit-testing - Apache 点燃 : test utilities

qt - 将单元测试项目添加到现有的 Qt Creator 项目

unit-testing - 如何编写Grails delete()方法的测试

php - 可以在 Laravel/PHPUnit 中模拟模型方法输出吗?

php - 使用 Point 类型的 PHPUnit/CakePHP Fixtures