Flexible Stub wrapper for PHPUnit's Mock Builder

Installs: 52 189 699

Dependents: 42

Suggesters: 0

Security: 0

Stars: 292

Watchers: 8

Forks: 17

Open Issues: 9

4.1.3 2024-02-02 19:21 UTC

This package is auto-updated.

Last update: 2024-05-01 00:12:53 UTC


CI Latest Stable Version Total Downloads License

Library on top of PHPUnit's mock builder providing a highly simplified syntax:


  • Stub - creating stub classes using static methods
  • Stub Trait - creating stubs and mocks using trait
  • Expected - defining expectations for mocks


Enabled by default in Codeception. For PHPUnit install this package:

composer require codeception/stub --dev


Stubs can be constructed with Codeception\Stub static calls:

// create a stub with find method replaced
$userRepository = Stub::make(UserRepository::class, ['find' => new User]);
$userRepository->find(1); // => User

// create a dummy
$userRepository = Stub::makeEmpty(UserRepository::class);

// create a stub with all methods replaced except one
$user = Stub::makeEmptyExcept(User::class, 'validate');

// create a stub by calling constructor and replacing a method
$user = Stub::construct(User::class, ['name' => 'davert'], ['save' => false]);

// create a stub by calling constructor with empty methods
$user = Stub::constructEmpty(User::class, ['name' => 'davert']);

// create a stub by calling constructor with empty methods
$user = Stub::constructEmptyExcept(User::class, 'getName', ['name' => 'davert']);
$user->getName(); // => davert
$user->setName('jane'); // => this method is empty
$user->getName(); // => davert 

See complete reference

Alternatively, stubs can be created by using Codeception\Test\Feature\Stub trait:

// ...


Mocks should be created by including Codeception\Test\Feature\Stub trait into a test case. Execution expectation are set with Codeception\Stub\Expected:

// find should be never called
$userRepository = $this->make(UserRepository::class, [
    'find' => Codeception\Stub\Expected::never()

// find should be called once and return a new user
$userRepository = $this->make(UserRepository::class, [
    'find' => Codeception\Stub\Expected::once(new User)