php:use “Mockery” to mock a static method called in another static method

微笑、不失礼 提交于 2019-12-10 14:48:22

问题


I want to mock a static method which has been used in another method using Mokcery,Just as follows:

Class SomeClass
{
   public static function methodA()
   {
     .....;
     self::B();
   } 
   public static function methodB()
   {
     Do SomeThing
   }
}

if I want to mock methodB,and use methodA,the mock function doesn't work, just because methodB is used in methodA,just as below

 use Mockery as m;
   $mocktest = m::mock->('SomeClass[B]');
   $mocktest->shouldReceive('B')->andReturn("expectedResult");
   $mocktest->methodA();

The code above will result in methodB still return it's original result rather than 'expectedResult'. I expect the methodB used in the methodA to be mocked,how could I operate?


回答1:


You need to use an alias to mock a static method:

$mock = \Mockery::mock('alias:SomeClass');

Note that class can't be loaded yet. Otherwise mockery won't be able to alias it.

More in the docs:

  • Mocking Public Static Methods
  • Quick Reference

Just be warned that mocking static methods is not a good idea. If you feel like you need it you have problem with design. Mocking the class you're testing is even worse and indicates your class has too many responsibilities.



来源:https://stackoverflow.com/questions/35910961/phpuse-mockery-to-mock-a-static-method-called-in-another-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!