Skip to content

trysettleup/can-make-or-fake

Repository files navigation

CanMakeOrFake

Latest Version on Packagist GitHub Tests Action Status Total Downloads

A lightweight Laravel trait that gives any class a make() static constructor (resolved through the container) and a fake() method for easy test mocking.

Installation

composer require settleup/can-make-or-fake

Usage

Add 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;
    }
}

Resolving instances with make()

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); // 1500

Faking in tests with fake()

fake() 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); // 0

Because fake() creates a partial mock, any methods you don't explicitly mock will still call the real implementation.

Conditionable

The trait includes Laravel's Conditionable trait, so you can use when() and unless():

$calculator = PriceCalculator::make();

$calculator->when($applyDiscount, function (PriceCalculator $calc) {
    // ...
});

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages