stevemoretz's avatar

spy on user method in query result

Here's a simplified version of what I'm trying to do.

class Something{
    function something(){
          foreach(User::all() as $user){
              $user->method();
          }
    }
}

And I want to spy if that method was called when something method on this class was called, but I can't mock User class as eloquent doesn't seem to be using it at all! method itself is tested in a unit test and here I just want to make sure that method is called a number of times that's all.

I couldn't figure out so far how to do this.

0 likes
9 replies
vincent15000's avatar

Why don't you set a counter and eventually store this counter in the database if you need, or log the counter value in the logs ?

$counter = 0;

foreach(User::all() as $user){
    $user->method();
	$counter = $counter + 1;
}

// store $counter ?
// log $counter ?
1 like
stevemoretz's avatar

@vincent15000 I should have mentioned that this query isn't a part of test, it is in a class somewhere on its own so I can't really do these kind of tricks.

1 like
MohamedTammam's avatar

Test the method effect instead of testing whether it's called or not.

1 like
stevemoretz's avatar

@MohamedTammam There is a huge amount of logic in that method which I test it on its own for a single user that's why here in this loop I'm just trying to check if that method is called.

1 like
vincent15000's avatar

@stevemoretz Perhaps another way is to store the counter in the session and retrieve it when you need to read it. You can do that from inside the method itself.

1 like
stevemoretz's avatar

@Snapey Thanks mocking the user model was the first thing I tried but that doesn't really work since eloquent still returned real instances instead of mocked ones, it's not using the service container I think here's a simple example:

        $mock = $this->mock(User::class);
        dd(User::first());

The output shows App\Models\User

1 like

Please or to participate in this conversation.