PHPUnit 模拟方法 returns null

PHPUnit mocked method returns null

我正在尝试使用 PHPUnit

测试以下 class
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        
    }
}

我的测试脚本如下:

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

对于我的测试脚本,我期望 stripe::charge() 方法的测试替身将完全按照原始 class 中定义的方式执行,而 stripe::requestStripe() 将 return 'Miaw'。因此,$stripe->charge('token') 也应该return 'Miaw'。但是,当我 运行 测试时,我得到:

Failed asserting that null matches expected 'Miaw'.

我该如何解决这个问题?

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

->setMethods(['requestStripe', 'charge'])

在您的情况下,您似乎想要部分模拟 class,以便 requestStripe() returns 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);

当你这样做时,你也可以指定你希望 requestStripe() 被调用的次数——这是一个额外的断言,不需要额外的努力,因为使用 $this->any() 不提供你有任何额外的好处。我在示例中使用了 $this->once()