Coder Social home page Coder Social logo

open-source-contributions / callable-fake Goto Github PK

View Code? Open in Web Editor NEW

This project forked from timacdonald/callable-fake

0.0 1.0 0.0 53 KB

A PHP testing utility that allows you to fake and capture invocations of a callable / Closure

License: MIT License

PHP 100.00%

callable-fake's Introduction

Callable / Closure testing fake

CI Mutation testing badge Latest Stable Version Total Downloads License

If you have an interface who's public API allows a developer to pass a Closure / callable, but causes no internal or external side-effects, as these are left up to the developer using the interface, testing it can create some duplicated boilerplate. This class wraps up that boilerplate and adds some named assertions. The named assertions gives you an API that is very much inspired by Laravel's service fakes. It may be a little more verbose, but it changes the language of the tests to better reflect what is going on.

Installation

You can install using composer from Packagist.

$ composer require timacdonald/callable-fake --dev

Basic usage

This packge requires you to be testing a pretty specfic type of API / interaction to be useful. Imagine you are developing a package that ships with the following interface...

interface DependencyRepository
{
    public function each(callable $callback): void;
}

This interface accepts a callback, and under the hood loops through all "dependecies" and passes each one to the callback for the developer to work with.

Before

Let's see what the a test for this method might look like...

public function testEachLoopsOverAllDependencies(): void
{
    // arrange
    $received = [];
    $expected = factory(Dependency::class)->times(2)->create();
    $repo = $this->app[DependencyRepository::class];

    // act
    $repo->each(function (Dependency $dependency) use (&$received): void {
        $received[] = $dependency;
    });

    // assert
    $this->assertCount(2, $received);
    $this->assertTrue($expected[0]->is($received[0]));
    $this->assertTrue($expected[1]->is($received[1]));
}

There is a bit of boilerplate in this test that can get repetitive when testing this kind of closure / callable API. This package aims to eliminate that boilerplate and also add some sytactic sugar over the assertions.

After

public function testEachLoopsOverAllDependencies(): void
{
    // arrange
    $callable = new CallableFake();
    $expected = factory(Dependency::class)->times(2)->create();
    $repo = $this->app[DependencyRepository::class];

    // act
    $repo->each($callable);

    // assert
    $callable->assertTimesInvoked(2);
    $callable->assertCalled(function (Depedency $dependency) use ($expected): bool {
        return $dependency->is($expected[0]);
    });
    $callable->assertCalled(function (Dependency $dependency) use ($expected): bool {
        return $dependency->is($expected[1]);
    });
}

Available assertions

All assertions are chainable.

assertCalled(callable $callback): self

$callable->assertCalled(function (Dependency $dependency): bool {
    return Str::startsWith($dependency->name, 'spatie/');
});

assertNotCalled(callable $callback): self

$callable->assertNotCalled(function (Dependency $dependency): bool {
    return Str::startsWith($dependency->name, 'timacdonald/');
});

assertCalledTimes(callable $callback, int $times): self

$callable->assertCalledTimes(function ($dependency): bool {
    return Str::startsWith($dependency, 'spatie/');
}, 999);

assertTimesInvoked(int $times): self

$callable->assertTimesInvoked(2);

assertInvoked(): self

$callable->assertInvoked();

assertNotInvoked(): self

$callable->assertNotInvoked();

Non-assertion API

asClosure(): Closure

If the method is type-hinted with \Closure instead of callable, you can use this method to transform the callable to an instance of \Closure.

$callable = new CallableFake;

$thing->closureTypeHintedMethod($callable->asClosure());

$callable->assertInvoked();

wasInvoked(): bool

if ($callable->wasInvoked()) {
    //
}

wasNotInvoked(): bool

if ($callable->wasNotInvoked()) {
    //
}

called(callable $callback): array

$invocationArguments = $callable->called(function (Dependency $dependency): bool {
    return Str::startsWith($dependency->name, 'spatie/')
});

Specifying return values

If you need to specify return values, this could be an indicator that this is not the right tool for the job. But there are some cases where return values determine control flow, so it can be handy, in which case you can pass a "return resolver" to the named constructor withReturnResolver.

$callable = CallableFake::withReturnResolver(function (Dependency $dependency): bool {
    if ($dependency->version === '*') {
        return '๐Ÿค ';
    }

    return '๐Ÿ˜€';
});

// You would not generally be calling this yourself, this is simply to demonstate
// what will happen under the hood...

$emoji = $callable(new Dependecy(['version' => '*']));

// $emoji === '๐Ÿค ';

Thanksware

You are free to use this package, but I ask that you reach out to someone (not me) who has previously, or is currently, maintaining or contributing to an open source library you are using in your project and thank them for their work. Consider your entire tech stack: packages, frameworks, languages, databases, operating systems, frontend, backend, etc.

callable-fake's People

Contributors

peter279k avatar timacdonald avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.