gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:18:06 26 4
gpt4 key购买 nike

我是单元测试的新手,在理解 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com