嘲弄 shouldReceive with type -> getting received object

Mockery shouldReceive with type -> getting received object

我对模拟和 phpunit 测试还很陌生。

我创建了一个测试来检查是否有东西被写入了数据库。我使用的是学说,我创建了一个模拟对象 doctrine_connection 和 doctrine_manager。

一切正常,但我想获取给定参数以使用 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 the EFPresentation->caption 但来自给定参数的给定对象。现在我正在使用在 add_presentation.

中创建的 EFPresentation->caption

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

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

需要注意的是,当测试未通过时,您将无法获得有关原因的任何详细信息,除非您添加一些回显或使用调试器。嘲讽会通知闭包 returned false.

编辑:编辑了缺失的括号