A lightweight Laravel trait that gives any class a make() static constructor (resolved through the container) and a fake() method for easy test mocking.
composer require settleup/can-make-or-fakeAdd the CanMakeOrFake trait to any class:
use SettleUp\CanMakeOrFake\CanMakeOrFake;
class PriceCalculator
{
use CanMakeOrFake;
public function calculate(int $quantity, int $unitPrice): int
{
return $quantity * $unitPrice;
}
}make() resolves the class through Laravel's service container, so any constructor dependencies are automatically injected:
$calculator = PriceCalculator::make();
$total = $calculator->calculate(quantity: 3, unitPrice: 500); // 1500fake() creates a Mockery partial mock and binds it into the container. Any subsequent call to make() (or container resolution) will return the mock:
use Mockery\MockInterface;
PriceCalculator::fake(function (MockInterface $mock) {
$mock->shouldReceive('calculate')->andReturn(0);
});
// Anywhere in your application that resolves PriceCalculator will now get the fake
$calculator = PriceCalculator::make();
$calculator->calculate(3, 500); // 0Because fake() creates a partial mock, any methods you don't explicitly mock will still call the real implementation.
The trait includes Laravel's Conditionable trait, so you can use when() and unless():
$calculator = PriceCalculator::make();
$calculator->when($applyDiscount, function (PriceCalculator $calc) {
// ...
});composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.