0

我的问题是:

我想通过模拟“getThirdPayUrlSpec”来测试“getThirdPayUrl”,如何使用 phpunit 创建一个模拟类?

class BasePayController{
    public static function getThirdPayUrl($type,$order,$arr,&$url){
        //$objCtrl = new AliPayController();
        $objCtrl = self::getPayController($type);
        $ret =  $objCtrl->getThirdPayUrlSpec($order,$arr,$url);
        return $ret;
    }   
}
4

2 回答 2

0

我的解决方法如下,首先php需要安装一个名为php-test-helper的插件

class BasePayControllerTest extends PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->getMock(
          'AliPayContoller',                    /* name of class to mock     */
          array('getThirdPayUrlSpec'),          /* list of methods to mock   */
          array(),                              /* constructor arguments     */
          'AliPayMock'                             /* name for mocked class     */
        );

        set_new_overload(array($this, 'newCallback'));   //php-test-helper  plug-in
    }

    protected function tearDown()
    {
        unset_new_overload();      //php-test-helper plug-in
    }

    protected function newCallback($className)
    {
        switch ($className) {
            case 'AliPayContoller': return 'AliPayMock';
            default:    return $className;
        }
    }

    public function testgetThirdPayUrl()
    {
        $foo = new BasePayController;
        $this->assertTrue($foo->getThirdPayUrl());
    }
}
?>
于 2013-07-26T07:36:47.000 回答
0

PHPUnit 手册有一节包含 Mock的示例。从这里开始,然后如果您遇到问题,请发布更详细的问题。

基本上,您的测试将模拟 BasePayController,并将返回一个硬设置 URL 进行测试。

<?php
require_once 'BasePayController.php';

class BasePayControllerTest extends PHPUnit_Framework_TestCase
{
    public function testThirdPartyURL()
    {
        // Create a stub 
        $stub = $this->getMockBuilder('BasePayController')
                     ->disableOriginalConstructor()
                     ->getMock();

        // Configure the stub.
        $stub->expects($this->any())
             ->method('getThirdPayUrl')
             ->will($this->returnValue('http://Dummy.com/URLToTest'));

        // Test the Stub
        $this->assertEquals('http://Dummy.com/URLToTest', $stub->getThirdPartyUrl());
    }
}
?>
于 2013-07-23T13:37:03.573 回答