开始使用PHP进行模拟

时间:2013-11-20 04:29:50

标签: php mocking phpunit

如何开始使用PHP模拟Web服务?我目前正在我的单元测试类中直接查询Web API,但这需要很长时间。有人告诉我你应该嘲笑服务。但是我该怎么做呢?我目前正在使用PHPUnit。 我想到的是简单地在文件系统中的某处保存静态结果(json或xml文件)并编写一个从该文件中读取的类。这是嘲弄有效吗?你能指出我可以帮助我的资源吗? PHPUnit足够还是需要其他工具?如果PHPUnit足够我需要查看PHPUnit的哪一部分?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您将模拟Web服务,然后测试返回的内容。您期望的硬编码数据是正确的,您将Mock设置为返回它,因此您的类的其他方法可能会继续使用结果。您可能还需要依赖注入以帮助进行测试。

class WebService {
    private $svc;

    // Constructor Injection, pass the WebService object here
    public function __construct($Service = NULL)
    {
        if(! is_null($Service) )
        {
            if($Service instanceof WebService)
            {
                $this->SetIWebService($Service);
            }
        }
    }

    function SetWebService(WebService $Service)
    {
        $this->svc = $Service
    }

    function DoWeb($Request)
    {
        $svc    = $this->svc;
        $Result = $svc->getResult($Request);
        if ($Result->success == false)
            $Result->Error = $this->GetErrorCode($Result->errorCode);
    }

    function GetErrorCode($errorCode) {
         // do stuff
    }
}

Test:

class WebServiceTest extends PHPUnit_Framework_TestCase
{
    // Simple test for GetErrorCode to work Properly
    public function testGetErrorCode()
    {
        $TestClass = new WebService();
        $this->assertEquals('One', $TestClass->GetErrorCode(1));
        $this->assertEquals('Two', $TestClass->GetErrorCode(2));
    }

    // Could also use dataProvider to send different returnValues, and then check with Asserts.
    public function testDoWebSericeCall()
    {
        // Create a mock for the WebService class,
        // only mock the getResult() method.
        $MockService = $this->getMock('WebService', array('getResult'));

        // Set up the expectation for the getResult() method 
        $MockService->expects($this->any())
                    ->method('getResult')
                    ->will($this->returnValue(1));      // Change returnValue to your hard coded results

        // Create Test Object - Pass our Mock as the service
        $TestClass = new WebService($MockService);
        // Or
        // $TestClass = new WebService();
        // $TestClass->SetWebServices($MockService);

        // Test DoWeb
        $WebString = 'Some String since we did not specify it to the Mock';  // Could be checked with the Mock functions
        $this->assertEquals('One', $TestClass->DoWeb($WebString));
    }
}

然后可以在其他函数中使用此模拟,因为返回是硬编码的,您的普通代码将处理结果并执行代码应该执行的工作(显示格式等)。这也可以为它编写测试。