PHPUnit: How to mock a function on a class?

后端 未结 2 961
情书的邮戳
情书的邮戳 2021-01-17 04:33

I have a class called \"QueryService\". On this class, there is a function called \"GetErrorCode\". Also on this class is a function called \"DoQuery\". So you can safely sa

2条回答
  •  佛祖请我去吃肉
    2021-01-17 05:20

    You need to use PHPUnit to create your Subject Under Test. If you tell PHPUnit which methods you would like to mock it mock only these method and the rest of class methods will stay as from original class.

    So an example test could look like this:

    public function testDoQuery()
    {
        $queryService = $this->getMock('\QueryService', array('GetErrorCode')); // this will mock only "GetErrorCode" method
    
        $queryService->expects($this->once())
            ->method('GetErrorCode')
            ->with($this->equalTo($expectedErrorCode));
    }
    

    Anyway, as answer above says, you should also use Dependency Injection pattern in order to make possible mock IntegratedService as well (because based on the example above you need to know $result->success value).

    So the right test should look like this:

    public function testDoQuery_Error()
    {
        $integratedService = $this->getMock('\IntegratedService', array('getResult'));
    
        $expectedResult = new \Result;
        $expectedResult->success = false;
    
        $integratedService->expects($this->any())
            ->method('getResult')
            ->will($this->returnValue($expectedResult));
    
        $queryService = $this->getMockBuilder('\QueryService')
            ->setMethods(array('GetErrorCode'))
            ->setConstructorArgs(array($integratedService))
            ->getMock();
    
        $queryService->expects($this->once())
            ->method('GetErrorCode')
            ->with($this->equalTo($expectedErrorCode))
            ->will($this->returnValue('expected error msg');
    
        $this->assertEquals($expectedResult->error, 'expected error msg');  
    }
    
    public function testDoQuery_Success()
    {
        $integratedService = $this->getMock('\IntegratedService', array('getResult'));
    
        $expectedResult = new \Result;
        $expectedResult->success = true;
    
        $integratedService->expects($this->any())
            ->method('getResult')
            ->will($this->returnValue($expectedResult));
    
        $queryService = $this->getMockBuilder('\QueryService')
            ->setMethods(array('GetErrorCode'))
            ->setConstructorArgs(array($integratedService))
            ->getMock();
    
        $queryService->expects($this->never())
            ->method('GetErrorCode');
    }
    

提交回复
热议问题