Mockery: how to use shouldReceive with method_exists?
Asked Answered
T

1

7

In my application code, I've got a method_exists check to authorize some hooking in a create process:

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

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

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

I'm trying to test this code, mocking $myClass and checking if $methodName is in fact called. Here's how I wrote the test:

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

But this isn't working, because method_exists is not defined in the mock. I'm fairly new to mock stuff, so maybe there's an obvious way to manage this problem, like "stubbing" the wanted function, but I wasn't able to find the way...

Thanks in advance for any help.

Thumbscrew answered 22/11, 2015 at 15:3 Comment(3)
The ListItemFactory source would be great to see.Clara
was just solving very similar stuff, check out #37927773 this might help youSupportable
This is what helped me: https://mcmap.net/q/212092/-stringcontains-argument-matching-within-laravel-log-facade-shouldreceiveAitchbone
F
0

Create a small testing class and mock it partially. Define in the scope of your test class:

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

Then, in your test function:

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

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

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

(in this example: use Mockery as m;)

Find answered 15/11, 2018 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.