PHPUnit mocked method called 0 times while it should be called once

泄露秘密 提交于 2019-12-24 03:05:56

问题


I'm new to unit-testing and I'm having problems understanding the mocking object in phpunit. I have the following function:

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

And now the uni-test for the function above:

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

But when I run the code I get the error:

   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.

What am I doing wrong?


回答1:


Your mock was never passed to the object you are testing. The thing you should remember is you don't mock a class, you mock an object of a class. So, you've created a mock, and then you have to pass it to your tested object somehow. In most cases you do it by depenedency injection.

In your original class inject dependency (through constructor for instance):

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

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

And then in your test:

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

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

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


来源:https://stackoverflow.com/questions/21428327/phpunit-mocked-method-called-0-times-while-it-should-be-called-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!