使用 Mockery 模拟另一个静态方法中调用的静态方法 [英] Use Mockery to mock a static method called in another static method

查看:54
本文介绍了使用 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,mock函数不起作用,只是因为methodA中使用了methodB,如下

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'.我希望methodA中使用的methodB被mock,我该怎么操作?

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.

文档中的更多内容:

请注意,模拟静态方法不是一个好主意.如果你觉得你需要它,那么你的设计就有问题.嘲笑你正在测试的班级更糟糕,表明你的班级有太多的责任.

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.

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

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