【问题标题】:PHPUnit mocked method returns nullPHPUnit 模拟方法返回 null
【发布时间】:2016-07-22 01:43:57
【问题描述】:

我正在尝试使用 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        
    }
}

我的测试脚本如下:

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() 方法的测试替身将完全按照原始类中的定义执行,并且 stripe::requestStripe() 将返回“Miaw”。因此,$stripe->charge('token') 也应该返回 'Miaw'。但是,当我运行测试时,我得到:

Failed asserting that null matches expected 'Miaw'.

我应该如何解决这个问题?

【问题讨论】:

  • 你没有设置charge方法返回任何东西,因此它返回null

标签: php unit-testing phpunit


【解决方案1】:

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

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

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

当您使用它时,您还可以指定您希望调用 requestStripe() 的次数 - 这是一个无需额外努力的额外断言,因为使用 $this->any() 不会为您提供任何额外的好处。我在示例中使用了$this->once()

【讨论】:

    猜你喜欢
    • 2011-09-30
    • 2020-01-21
    • 1970-01-01
    • 2016-03-21
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多