PHPUnit mocked方法返回null

Kam*_*han 5 php phpunit unit-testing

我试图使用PHPUnit测试下面的类

class stripe extends paymentValidator {
    public $apiKey;

    public function __construct ($apiKey){
        $this->apiKey = $apiKey;
    }

    public function charge($token) {
        try {
            return $this->requestStripe($token);
        } catch(\Stripe\Error\Card $e) {
            echo $e->getMessage();
            return false;
        }
    }

    public function requestStripe($token) {
        // do something        
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试脚本如下所示:

class paymentvalidatorTest extends PHPUnit_Framework_TestCase
{
   /**
    * @test
    */
    public function test_stripe() {
        // Create a stub for the SomeClass class.
        $stripe = $this->getMockBuilder(stripe::class)
            ->disableOriginalConstructor()
            ->setMethods(['requestStripe', 'charge'])
            ->getMock();

        $stripe->expects($this->any())
            ->method('requestStripe')
            ->will($this->returnValue('Miaw'));

        $sound = $stripe->charge('token');
        $this->assertEquals('Miaw', $sound);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用我的测试脚本,我期望stripe :: charge()方法的测试双精度与原始类中的定义完全相同,而stripe :: requestStripe()将返回'Miaw'.因此,$ stripe-> charge('token')也应该返回'Miaw'.但是,当我运行测试时,我得到:

Failed asserting that null matches expected 'Miaw'.
Run Code Online (Sandbox Code Playgroud)

我该怎么解决这个问题?

Rob*_*ill 7

在你调用的地方setMethods,你告诉PHPUnit模拟类应该模拟这些方法的行为:

->setMethods(['requestStripe', 'charge'])
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你看起来想要部分模拟类,所以requestStripe()返回Miaw,但你想charge运行它的原始代码 - 你应该charge从模拟的方法中删除:

$stripe = $this->getMockBuilder(stripe::class)
    ->disableOriginalConstructor()
    ->setMethods(['requestStripe'])
    ->getMock();

$stripe->expects($this->once())
    ->method('requestStripe')
    ->will($this->returnValue('Miaw'));

$sound = $stripe->charge('token');
$this->assertEquals('Miaw', $sound);
Run Code Online (Sandbox Code Playgroud)

当你在它的时候,你也可以指定你期望requestStripe()被调用的次数 - 这是一个额外的断言,没有额外的努力,因为使用$this->any()不会为你提供任何额外的好处.我已经$this->once()在示例中使用了.