Stubs are objects used to fake dependencies in code under test. They respond
to interactions with fixed behavior or act as simple placeholders, decoupling
the real implementation. To create a stub, you must provide a loadable class,
trait, or interface. The object you receive serves as the pseudo dependency
that extends, uses, or implements the given type. Pass the stub directly to
your code when using it as a placeholder. For stubs with fixed behavior,
obtain a builder via the fake method to configure them:
$example = $this->createStub(Example::class);
$example->fake("<methodToFake>");
Note
The entrypoint fake is reserved method name for stubs.
Logical Method Groups
The builder API provides a chainable interface with two logical method groups that define encapsulated interactions. In the prebuilt group, you can set references and return values:
set(<param>: <value>): Set value by reference using named params.return: Return value.
For individual operations, use the custom closure group:
hook: Execute custom logic.
Note
The custom closure must declare all parameters of the faked method, because Reflex passes all arguments through.
Progressive Interactions
Interactions between the code under test and the stubbed dependency are progressive. To handle each call, you can define sequences of logical groups that are applied in order:
$example->fake("example")
// first call
// custom group
->hook(function (string &$example) {
$example = "value"
return "value";
})
// calls 2 - 4
// prebuilt group
->set(example: "value")
->return("value")
->repeat(2)
// last call
// prebuilt group
// inherits previous set and
// starts new group by repetition since
// return already exists
->return("other-value");
Logical Group Types
The first call is handled by a custom logical group. The callback receives
the method argument by reference, assigns it a value, and returns a result.
The next group uses the prebuilt logical group. It sets the argument by
reference and returns a fixed value. The repeat call repeats the current
group for two additional calls.
Inheritance & Duplication
Whenever a prebuilt method is duplicated, a new logical group is created.
This new group inherits any missing methods from the previous group and
allows you to override only the behavior you want to change. In the example
above, the final return call duplicates a method from the previous group,
starting a new logical group. It inherits the argument setup defined earlier
but overrides the result value.
Note
Duplicated prebuilt methods create new logical groups, inheriting missing methods from the previous group automatically.