Mocks: Asserting a Class is Used
When Laravel doesn't give you a native assertion
What can we do when Laravel doesn't provide a native assertion? We can use mocks.
Controller
// app/Http/Controllers/UserController.php
public function store(CreateUserRequest $request, CreateUserAction $action)
{
$user = $action->execute($request->validated());
return redirect()->route('users.show', $user);
}
Feature Test
// tests/Feature/Http/Controllers/UserController/StoreTest.php
$mock = $this->createMock(CreateUserAction::class);
$mock->expects($this->once())
->method('execute')
->with($this->anything());
$this->app->instance(CreateUserAction::class, $mock);
$this->post(route('users.store'), $data);
Laravel has no assertActionExecuted(), so we mock CreateUserAction to verify it's called.