Rodrigo Balest
Rodrigo Balest

Reputation: 336

PHP Mockery: how to set expectation on a method OR another method?

I'm trying to use Mockery and PHPUnit to test if one method OR another method of a given class will be called when some piece of code is executed.

This is exactly what I'm trying to do (I'm using Laravel 5):

// Test an email is sent to new user
// upon account creation.
public function testEmailSentOnNewUserCreation()
{
    // Mail can be sent right on ...
    Mail::shouldReceive('send')->once(); //...OR...
    // ... it can be queued for later.
    Mail::shouldReceive('queue')->once();
    // I'm ignoring parameters and returning values here
    // for sake of brevity.

    $u = new User;
    $u->name = 'Jon Doe';
    $u->email = '[email protected]';
    $u->save();
}

So, my question is about how to implement the OR part, if it's possible. I also searched for some PHPUnit annotation that could be helpful, but I couldn't find anything.

Upvotes: 1

Views: 317

Answers (1)

gontrollez
gontrollez

Reputation: 6538

One of the paradigms of unit testing is that you should be in control of the exact flow for each test case you implement. That's why no if, switch, etc should appear in your test.

Whenever the object under test behaviour depends on another object, or on a given condition (which logically is more or less the same), the dependency must be mocked in order to take control of the case you're testing.

So, in your case, you should mock the dependency that makes your class invoke the send or queue methods.

I think that's why testing frameworks do not implement what you intended to use.

Upvotes: 1

Related Questions