php:use"Mockery";模拟另一个静态方法中调用的静态方法 [英] php:use "Mockery" to mock a static method called in another static method

查看:248
本文介绍了php:use"Mockery";模拟另一个静态方法中调用的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟一个静态方法,该方法已在使用Mokcery的另一种方法中使用,如下所示:

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
   }
}

如果我想模拟methodB并使用methodA,则模拟功能不起作用,只是因为methodB在methodA中使用,如下所示

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();

上面的代码将导致methodB仍返回其原始结果,而不是'expectedResult'. 我希望方法A中使用的方法B被嘲笑,我该如何操作?

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?

推荐答案

您需要使用别名来模拟静态方法:

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.

文档中的更多信息:

  • 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.

这篇关于php:use"Mockery";模拟另一个静态方法中调用的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆