codeception/stub
Create lightweight test doubles for PHP with Codeception Stub. Quickly generate stubs and mocks, define method returns and expectations, and override behavior on the fly—ideal for unit tests that need fast, flexible objects without full implementations.
Start by installing via Composer: composer require --dev codeception/stub. In your test class, use Codeception\Stub to quickly generate stubs. For example:
use Codeception\Stub;
// Create a stub of a service class
$userService = Stub::make(UserService::class, [
'findUserById' => $mockUser,
'isValid' => true
]);
The simplest first use case: stub a method on a real class to return a fixed value without invoking its actual logic—e.g., mocking database or API calls in a unit test.
Stub::make() to override specific methods. Use Stub::construct() for full constructor-based construction with stubbed methods.Stub::make(Service::class, [
'getCacheKey' => function($id) { return "cache:$id"; }
]);
Stub::invoke() to call a method directly and chain Stub::getInvokedMethods() or Stub::getArguments() to assert interaction history in your test.assertNotNull($stub) or assertEquals()—no need for separate mock expectations syntax.Stub::make() skips constructor calls. Use Stub::construct() if dependencies need initialization.Stub::getInvokedMethods() and Stub::getArguments($methodName) are invaluable for asserting how a stub was used—but remember to call them after the method under test.Stub to create project-specific helpers (e.g., TestDouble::service()), promoting consistency across teams.Stub shines for state-based testing, not behavior-based.How can I help you explore Laravel packages today?