【问题标题】:Mockery shouldReceive with type -> getting received object嘲弄 shouldReceive 类型 -> 获取接收到的对象
【发布时间】:2015-11-22 20:53:03
【问题描述】:

我对嘲弄和 phpunit 测试很陌生。

我创建了一个测试来检查是否将某些内容写入数据库。我使用了学说,并创建了我的学说连接和学说管理器的模拟对象。

一切正常,但我想获取给定的参数以使用 assertEqual 进行检查。

现在我正在做以下事情:

require_once "AbstractEFlyerPhpUnitTestCase.php";
class test2 extends AbstractEFlyerPhpUnitTestCase {

public function getCodeUnderTest() {
    return "../php/ajax/presentations/add_presentation.php";
}

public function testingPresentationObject()
 {
    // prepare
    $_REQUEST["caption"] = "Testpräsentation";
    $_SESSION["currentUserId"] = 1337;

    $this->mockedUnitOfWork->shouldReceive('saveGraph')->with(\Mockery::type('EFPresentation'));
    $this->mockedUnitOfWork->shouldReceive('saveGraph')->with(\Mockery::type('EFSharedPresentation'));
    $this->mockedDoctrineConnection->shouldReceive('commit');

    //run
    $this->runCodeUnderTest();
    global $newPresentation;
    global $newSharedPresentation;
    // verify
    $this -> assertEquals($newPresentation->caption,$_REQUEST["caption"]);
    $this -> assertEquals($newSharedPresentation->userId,$_SESSION["currentUserId"]);
 }
}

saveGraph 正在获取一个 EFPresentation 对象。我想要的是对象。

我想 assertEqual EFPresentation->caption 但来自给定对象的参数。现在我正在使用在 add_presentation 中创建的 EFPresentation->caption。

【问题讨论】:

    标签: php phpunit mockery


    【解决方案1】:

    您可以使用 \Mockery::on(closure) 来检查参数。此方法接收一个函数,该函数将被调用并传递实际参数。在里面你可以检查你需要的任何东西,如果检查成功,你必须返回true。

    $this
      ->mockedUnitOfWork
      ->shouldReceive('saveGraph')
      ->with(
          \Mockery::on(function($newPresentation) {
              // here you can check what you need...
              return $newPresentation->caption === $_REQUEST["caption"];
          })
      )
    ;
    

    需要注意的是,当测试未通过时,您将无法获得任何详细信息来说明原因,除非您放置一些回显或使用调试器。 Mockery 会通知闭包返回 false。

    编辑:编辑缺少的括号

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2016-02-24
      • 2019-02-09
      • 2014-01-16
      • 2020-09-14
      • 2018-10-31
      • 2016-06-22
      • 2019-08-03
      • 2015-01-26
      相关资源
      最近更新 更多