prophecy: Trait method not being found?

I have a trait on a class which shouldBeCalled how ever this prophecy is fine but when the tested code runs it says it doesn’t exist on the object.

My trait

trait AppliesEvents
{
  public function apply(AggregateChanged $event);
}

My class (gets mocked)

class Deal
{
  use AppliesEvents;
}

My test code:

    public function it_will_apply_unlist_deal_event_on_deal($deals, UnlistDealCommand $command, Deal $deal)
    {
        $deals->findByKey('123')->willReturn($deal);
        $command->dealId()->willReturn('123');
        $deal->apply(Argument::type(UnlistDeal::class))->shouldBeCalled();

        $this->handle($command);
    }

The code being tested:

    /**
     * @param UnlistDealCommand $command
     */
    public function handle(UnlistDealCommand $command)
    {
        $deal = $this->deals->findByKey($command->dealId());

        if (is_null($deal)) {
            throw new \RuntimeException('Unable to locate deal.');
        }

        $deal->apply(new UnlistDeal);

        $this->deals->persist($deal);
    }

If I var_dump($deal) I can see $methodProphecies contaons apply but when I call it I get

it will apply unlist deal event on deal
method `Double\Deal\P4::apply()` not found.

Any ideas?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 16 (5 by maintainers)

Most upvoted comments

Closing for inactivity.

I’m also having a similar problem. Let’s say:

trait DefinitionTrait {

 protected $definition;

 public getDefinition($type) {
  return something;
 }
}

and my using class

class DefinitionUser {
   use DefinitionTrait;

  public someMethod() {

  }

  ....
}

Using PHPUnit, I can do something like this:

  $mock1 = $this->prophesize(DefinitionUser::class);

  $mock1->someMethod()->willReturn('bingo');
  $mock1->getDefinition(Argument::any())->willReturn([ 'id' => 'ego']);

  $this->awayWeGo($mock1->reveal());

It turns out that someMethod() will be handled by Prophecy, but the getDefinition() promise will never be used at all. As near as I can tell, Prophecy just ignores it.

I’m guessing this is part of the problem here. Is there a work-around?

I know PhpUnit allows you to partially mock a class, even methods in the class you’re testing, but from an OO perspective it would be wrong to consider a method in a Trait anything other than a method added to the SUT (the class you’re testing).

If you are stubbing/mocking behaviour, then that behaviour belongs to a different class (which might use your trait)