2

我一直在关注 phpUnit 的教程,但我似乎无法让它工作。

这是链接:

https://jtreminio.com/2013/03/unit-testing-tutorial-part-4-mock-objects-stub-methods-dependency-injection/

There was 1 error:

1) phpUnitTutorial\Test\PaymentTest::testProcessPaymentReturnsTrueOnSuccess
ReflectionException: Class Mock_AuthorizeNetAIM_2d93f549 does not have a constructor, so     you cannot pass any constructor arguments

phpUnitTutorial/Payment.php

<?php

namespace phpUnitTutorial;

class Payment
{
    const API_ID = 123456;
    const TRANS_KEY = 'TRANSACTION KEY';

    //Use Dependency Injection
    public function processPayment(\AuthorizeNetAIM $transaction, array $paymentDetails)
    {
        $transaction->amount = $paymentDetails['amount'];
        $transaction->card_num = $paymentDetails['card_num'];
        $transaction->exp_date = $paymentDetails['exp_date'];

        $response = $transaction->authorizeAndCapture();

        if ($response->approved) {
            return $this->savePayment($response->transaction_id);
        }

        throw new \Exception($response->error_message);
    }

    public function savePayment($transactionId)
    {
        // Logic for saving transaction ID to database or anywhere else would go in here
        return true;
    }
}

phpUnitTutorial/Test/PaymentTest.php

<?php

namespace phpUnitTutorial\Test;

require_once __DIR__ . '/../Payment.php';
use phpUnitTutorial\Payment;

class PaymentTest extends \PHPUnit_Framework_TestCase
{

    public function testProcessPaymentReturnsTrueOnSuccess()
    {
        $paymentDetails = array(
            'amount' => 123.99,
            'card_num' => '4111-111-111-111',
            'exp_date' => '03/2013'
        );

        $payment = new Payment();

        // Note stdClass is used to conveniently create a generic
        // class
        $response = new \stdClass();
        $response->approved = true;
        $response->transaction_id = 123;

        $authorizeNet = $this->getMockBuilder('\AuthorizeNetAIM')
             ->setConstructorArgs(
                 array(
                     $payment::API_ID,
                     $payment::TRANS_KEY
                 )
             )->getMock();

        // $authorizeNet =  $this
        //     ->getMock(
        //         '\AuthorizeNetAIM',
        //         array(),
        //         array($payment::API_ID, $payment::TRANS_KEY)
        //     );

        $authorizeNet->expects($this->once())
            ->method('authorizeAndCapture')
            ->will($this->returnValue($response));

        $result = $payment->processPayment($authorizeNet, $paymentDetails);

        $this->assertTrue($result);
    }
}
4

1 回答 1

1

\AuthorizeNetAIM没有构造函数 - 如错误消息所述。所以你不能向它传递任何参数。以这种方式创建模拟:

$authorizeNet = $this->getMockBuilder('\AuthorizeNetAIM')->getMock();

或更短:

$authorizeNet = $this->getMock('\AuthorizeNetAIM');
于 2013-10-28T09:59:59.277 回答