【问题标题】:Mockery: how to use shouldReceive with method_exists?嘲弄:如何将 shouldReceive 与 method_exists 一起使用?
【发布时间】:2016-02-24 16:25:55
【问题描述】:

在我的应用程序代码中,我有一个 method_exists 检查以授权在创建过程中进行一些挂钩:

// Note: $myClass is implementing a ListItemFactory interface.

if ($isCreate) {
  $methodName = "create{$attr}ListItem";

  if (method_exists($myClass, $methodName)) {
    $item = $myClass->$methodName();
  } else {
    [...]
  }
}

我正在尝试测试这段代码,模拟$myClass 并检查$methodName 是否确实被调用。以下是我编写测试的方式:

/** @test */
function specific_create_method_is_called()
{
  $factory = Mockery::mock(ListItemFactory::class)->makePartial();
  $factory->shouldReceive("createCommentsListItem")->once();
  [...]
}

但这不起作用,因为method_exists 没有在模拟中定义。我对模拟东西还很陌生,所以也许有一种明显的方法来管理这个问题,比如“存根”想要的功能,但我找不到方法......

提前感谢您的帮助。

【问题讨论】:

标签: php unit-testing testing mockery


【解决方案1】:

创建一个小型测试类并对其进行部分模拟。 在测试类的范围内定义:

class MyClass implements ListItemFactory {
  public function createCommentsListItem() { } 
}

然后,在你的测试函数中:

/** @test */
function specific_create_method_is_called() 
{
  $myClass = m::mock(MyClass::class)->makePartial();

  $myClass->shouldReceive('createCommentsListItem')->once();

  // method_exists($myClass, 'createCommentsListItem')
  //   returns true now
}

(在本例中:use Mockery as m;

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2013-04-08
    • 2015-11-22
    • 2014-08-19
    • 2020-09-06
    • 2017-09-01
    • 2016-08-08
    • 2019-08-03
    • 2014-10-27
    相关资源
    最近更新 更多