phpphpunitmockery

Mockery shouldReceive with type -> getting received object


Im quite new to mockery and phpunit testing.

I created a test to check if something would have been written to a database. Im using doctrine and I created a mocked object of my doctrine_connection and my doctrine_manager.

Everything works so fine BUT I want to get the given parameter to check it with assertEqual.

Right now im doing the following:

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 is getting an EFPresentation Object. What I want is the object.

I want to assertEqual the EFPresentation->caption but from the given object given to the parameter. Right now I'm using the EFPresentation->caption which is created in the add_presentation.


Solution

  • You can use \Mockery::on(closure) to check the arguments. This method receives a function that will be called passing the actual argument. Inside you can check whatever you need, and you must return true if the check was successful.

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

    One caveat is that when the test does not pass, you won't get any detailed information on why, unless you put some echoes or use the debugger. Mockery will inform that the closure returned false.

    Edit: edited missing bracket