【问题标题】:PHPUnit: how to mock one specific method in class which is called from not mocked onePHPUnit:如何在类中模拟一种特定方法,该方法从未模拟的方法中调用
【发布时间】:2014-09-18 12:46:21
【问题描述】:

有如下类:

class MyClass{     

     public static function create($data){


         $dataModified= $self::doCurlRequest($data);

         //doing something else with data

         return $dataModifiedAlot;
     }

     public static function doCurlRequest($someData){
         //doing request here
     }

 }

是否可以只模拟 doCurlRequest($someData)?我试过这个:

class MyClassTest extends PHPUnit_Framework_TestCase{     

     public function testCreate(){

         $mock = $this->getMockBuilder('MyClass')->setMethods(array('doCurlRequest'))->getMock();

         $mock::staticExpects($this->any())
                ->method('doCurlRequest')
                ->with($someDataNeededForRequest)
                ->will($this->returnValue("some JSON rensponse"));

         $response = $mock::create($data);       

     }

 }

问题是 doCurlRequest($someData) 方法返回实际值而不是预期值:/ 我做错了什么?

【问题讨论】:

    标签: php mocking phpunit static-methods


    【解决方案1】:

    您需要使用static::doCurlRequest() 在您的类中调用该方法。 staticExpects 使用 late static binding 创建模拟。因此,需要通过static 调用该方法,而不是通过self 或$this-> 调用实际方法。

    您的班级需要如下所示:

    class MyClass{     
    
         public static function create($data){
    
    
             $dataModified= static::doCurlRequest($data);
    
             //doing something else with data
    
             return $dataModifiedAlot;
         }
    
         public static function doCurlRequest($someData){
             //doing request here
         }
    
     }
    

    仅供参考:staticExpects 在 PHPUnit 4.0 中被删除

    https://github.com/sebastianbergmann/phpunit/wiki/Release-Announcement-for-PHPUnit-4.0.0#backwards-compatibility-issues

    【讨论】:

    • 太好了,谢谢。顺便说一句,我知道 staticExpects,但我使用的是 PHPUnit 3.7 :)
    猜你喜欢
    • 2013-09-12
    • 1970-01-01
    • 2020-11-15
    • 2019-08-07
    • 1970-01-01
    • 2019-07-29
    • 2018-05-26
    • 2020-02-17
    • 2021-06-16
    相关资源
    最近更新 更多