PHPackages                             soyhuce/laravel-testing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. soyhuce/laravel-testing

ActiveLibrary[Testing &amp; Quality](/categories/testing)

soyhuce/laravel-testing
=======================

Helpers for Laravel tests

2.14.0(2mo ago)314.2k↓33.3%1[2 PRs](https://github.com/Soyhuce/laravel-testing/pulls)1MITPHPPHP ^8.3CI passing

Since Mar 3Pushed 1mo ago4 watchersCompare

[ Source](https://github.com/Soyhuce/laravel-testing)[ Packagist](https://packagist.org/packages/soyhuce/laravel-testing)[ Docs](https://github.com/soyhuce/laravel-testing)[ GitHub Sponsors](https://github.com/soyhuce)[ RSS](/packages/soyhuce-laravel-testing/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (15)Versions (31)Used By (1)

Helpers for Laravel tests
=========================

[](#helpers-for-laravel-tests)

[![Latest Version on Packagist](https://camo.githubusercontent.com/79c3fb3a6b28b2c4bfe884d866273aa3b38f104de1d53e9d2708f86749de4d16/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736f79687563652f6c61726176656c2d74657374696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/soyhuce/laravel-testing)[![GitHub Tests Action Status](https://camo.githubusercontent.com/581c39bf3e37f82051d440b074c6754f5a912ed28e7dc3c7d3cfdd76cc254c4e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f79687563652f6c61726176656c2d74657374696e672f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/soyhuce/laravel-testing/actions/workflows/run-tests.yml)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/77b126a823c46e135d57e0f6571b0ef26ff1b8b093c5232ce0f977ac707c2549/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f79687563652f6c61726176656c2d74657374696e672f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d7068707374616e267374796c653d666c61742d737175617265)](https://github.com/soyhuce/laravel-testing/actions/workflows/phpstan.yml)[![GitHub PHPStan Action Status](https://camo.githubusercontent.com/755945da617f9db644d620c46c8b39b0911ea285e18e6ea2bab37a60d65d81f3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f79687563652f6c61726176656c2d74657374696e672f7068702d63732d66697865722e796d6c3f6272616e63683d6d61696e266c6162656c3d7068702d63732d6669786572267374796c653d666c61742d737175617265)](https://github.com/soyhuce/laravel-testing/actions/workflows/php-cs-fixer.yml)[![Total Downloads](https://camo.githubusercontent.com/ca26fe16683bd25c42623f1e4265cf4ed15d73fa5d53e2a83ec801ee92237769/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f736f79687563652f6c61726176656c2d74657374696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/soyhuce/laravel-testing)

Extra tools for your laravel tests

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require soyhuce/laravel-testing --dev
```

Usage
-----

[](#usage)

### Laravel assertions

[](#laravel-assertions)

To use Laravel specific assertions, you will have to add `\Soyhuce\Testing\Assertions\LaravelAssertions::class` trait to your test class.

#### assertModelIs

[](#assertmodelis)

Matches if the model is equal to the given model.

```
/** @test */
public function myTest()
{
    $user1 = User::factory()->createOne();
    $user2 = User::find($user1->id);

    $this->assertIsModel($user1, $user2);
}
```

#### assertCollectionEquals

[](#assertcollectionequals)

Matches if the collections are equal.

```
$collection1 = new Collection(['1', '2', '3']);
$collection2 = new Collection(['1', '2', '3']);
$this->assertCollectionEquals($collection1, $collection2);
```

2 Collections are considered equal if they contain the same elements, indexed by the same keys and in the same order.

```
$this->assertCollectionEquals(new Collection([1, 2]), new Collection([1, 2, 3])); // fail
$this->assertCollectionEquals(new Collection([1, 2, 3]), new Collection([1, 2])); // fail
$this->assertCollectionEquals(new Collection([1, 2, 3]), new Collection([3, 1, 2])); // fail
$this->assertCollectionEquals(new Collection([1, 2, 3]), new Collection([3, 1, 2])); // fail
$this->assertCollectionEquals(new Collection([1, 2, 3]), new Collection([1, 2, "3"])); // fail
$this->assertCollectionEquals(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'b' => 2])); // fail
$this->assertCollectionEquals(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'b' => 2, 'c' => 4])); // fail
$this->assertCollectionEquals(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'b' => 2, 'd' => 3])); // fail
$this->assertCollectionEquals(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'c' => 3, 'b' => 2])); // fail
$this->assertCollectionEquals(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'b' => 2, 3])); // fail
```

If the Collections contain Models, `assertCollectionEquals` will use Model comparison of `assertIsModel`.

```
$user1 = User::factory()->createOne();
$user2 = User::find($user1->id);
$this->assertCollectionEquals(collect([$user1]), collect([$user2])); // Success
```

You can give an array in the `$expected` parameter of `assertCollectionEquals` :

```
/** @test */
public function theUsersAreOrdered(): void
{
    $user1 = User::factory()->createOne();
    $user2 = User::factory()->createOne();

    $this->assertCollectionEquals(
        [$user1, $user2],
        User::query()->orderByDesc('id')->get()
    );
}
```

#### assertCollectionEqualsCanonicalizing

[](#assertcollectionequalscanonicalizing)

Matches if the collections are canonically equals.

```
$collection1 = new Collection(['1', '2', '3']);
$collection2 = new Collection(['3', '2', '1']);
$this->assertCollectionEqualsCanonicalizing($collection1, $collection2);
```

2 Collections are considered equal if they contain the same elements, indexed by the same keys.

```
$this->assertCollectionEqualsCanonicalizing(new Collection([1, 2]), new Collection([1, 2, 3])); // fail
$this->assertCollectionEqualsCanonicalizing(new Collection([1, 2, 3]), new Collection([1, 2])); // fail
$this->assertCollectionEqualsCanonicalizing(new Collection([1, 2, 3]), new Collection([1, 2, "3"])); // fail
$this->assertCollectionEqualsCanonicalizing(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'b' => 2])); // fail
$this->assertCollectionEqualsCanonicalizing(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'b' => 2, 'c' => 4])); // fail
$this->assertCollectionEqualsCanonicalizing(new Collection(['a' => 1, 'b' => 2, 'c' => 3]), new Collection(['a' => 1, 'b' => 2, 3])); // fail
```

If the Collections contain Models, `assertCollectionEqualsCanonicalizing` will use Model comparison of `assertIsModel`.

```
$user1 = User::factory()->createOne();
$user2 = User::find($user1->id);
$this->assertCollectionEqualsCanonicalizing(collect([$user1]), collect([$user2])); // Success
```

You can give an array in the `$expected` parameter of `assertCollectionEqualsCanonicalizing` :

```
/** @test */
public function theUsersAreOrdered(): void
{
    $user1 = User::factory()->createOne();
    $user2 = User::factory()->createOne();

    $this->assertCollectionEqualsCanonicalizing(
        [$user1, $user2],
        User::query()->get()
    );
}
```

### TestResponse assertions

[](#testresponse-assertions)

All these methods are available in `Illuminate\Testing\TestResponse`:

#### Contract Testing

[](#contract-testing)

Requires [hotmeteor/spectator](https://github.com/hotmeteor/spectator/) package

- `TestResponse::assertValidContract(int $status)` : Verifies that the request and the response are valid according to the contract.

#### Data

[](#data)

- `TestResponse::assertData($expect)` : Alias for `assertJsonPath('data', $expect)`
- `TestResponse::assertDataPath(string $path, $expect)` : Alias for `assertJsonPath('data.'.$path, $expect)`
- `TestResponse::assertDataPaths(array $expectations)` : Runs `assertDataPath` for each `$path` =&gt; `$expect` pair in the array.
- `TestResponse::assertDataPathCanonicalizing(string $path, array $expect)` : Alias for `assertJsonPathCanonicalizing('data.'.$path, $expect)`
- `TestResponse::assertDataPathsCanonicalizing(array $expectations)` : Runs `assertDataPathCanonicalizing` for each `$path` =&gt; `$expect` pair in the array.
- `TestResponse::assertDataMissing($item)` : Alias for `assertJsonMissingPath('data', $item)`
- `TestResponse::assertDataPathMissing(string $path, $item)` : Alias for `assertJsonMissingPath('data.'.$path, $item)`

#### Json

[](#json)

- `TestResponse::assertJsonPathMissing(string $path, $item)` : Verifies that the Json path does not contain `$item`
- `TestResponse::assertJsonMessage(string $message)` : Alias for `assertJsonPath('message', $message)`
- `TestResponse::assertSimplePaginated()` : Verifies that the response is a simple paginated response.
- `TestResponse::assertPaginated()` : Verifies that the response is a paginated response.

#### View

[](#view)

- `TestResponse::assertViewHasNull(string $key)` : Verifies that the key is present in the view but is null.

### FormRequest test in isolation

[](#formrequest-test-in-isolation)

It's possible to test FormRequests in isolation thanks to the `TestsFormRequests` trait.

```
$testFormRequest = $this->createRequest(CreateUserRequest::class);
```

`$testFormRequest` have some methods to check authorization and validation of the request.

- `TestFormRequest::by(Authenticable $user, ?string $guard = null)` : set authenticated user in the request
- `TestFormRequest::withParams(array $params)` : set route parameters
- `TestFormRequest::withParam(string $param, mixed $value)` : set a route parameter
- `TestFormRequest::validate(array $data): TestValidationResult` : get Validation result
- `TestFormRequest::assertAuthorized()` : assert that the request is authorized
- `TestFormRequest::assertUnauthorized()` : assert that the request is unauthorized
- `TestValidationResult::assertPasses()` : assert that the validation passes
- `TestValidationResult::assertFails(array $errors = [])` : assert that the validation fails
- `TestValidationResult::assertValidated(array $expected)` : assert that the attributes and values that passed validation are the expected ones

For exemple :

```
$this->createRequest(CreateUserRequest::class)
    ->validate([
        'name' => 'John Doe',
        'email' => 'john.doe@email.com',
    ])
    ->assertPasses();

$this->createRequest(CreateUserRequest::class)
    ->validate([
        'name' => null,
        'email' => 12,
    ])
    //->assertFails() We can check that the validation fails without defining the fields nor error messages
    ->assertFails([
        'name' => 'The name field is required.',
        'email' => [
            'The email must be a string.',
            'The email must be a valid email address.',
        ]
    ]);

$this->createRequest(CreateUserRequest::class)
    ->by($admin)
    ->assertAuthorized();

$this->createRequest(CreateUserRequest::class)
    ->by($user)
    ->assertUnauthorized();

$this->createRequest(UpdateUserRequest::class)
    ->withArg('user', $user)
    ->validate([
        'email' => 'foo@email.com'
    ])
    ->assertPasses();
```

### JsonResource test in isolation

[](#jsonresource-test-in-isolation)

It's possible to test the `JsonResources` in isolation thanks to the `TestsJsonResources` trait.

`TestsJsonResources::createResponse(JsonResource $resource, ?Request $request = null)` returns a `Illuminate\Testing\TestResponse`.

```
$this->createResponse(UserResource::make($user))
    ->assertData([
        'id' => $user->id,
        'name' => $user->name,
        'email' => $user->email,
    ]);
```

### Matcher

[](#matcher)

Let's take this test

```
$user = User::factory()->createOne();

$this->mock(DeleteUser::class)
    ->shouldReceive('execute')
    ->withArgs(function(User $executed) use ($user) {
        $this->assertIsModel($user, $executed);

        return true;
    })
    ->once();

// run some code wich will execute the mock
```

We can simplify this test by using a `Matcher`.

```
$this->mock(DeleteUser::class)
    ->shouldReceive('execute')
    ->withArgs(Matcher::isModel($user))
    ->once();
```

For Collections, we can use `Matcher::collectionEquals()` or `Matcher::collectionEqualsCanonicalizing()`.

For more complex cases, we can use `Matcher::make`.

```
$user = User::factory()->createOne();
$roles = Role::factory(2)->create();

$this->mock(UpdateUser::class)
    ->shouldReceive('execute')
    ->withArgs(function(User $executed, string $email, Collection $executedRoles) use ($user, $roles) {
        $this->assertIsModel($user, $executed);
        $this->assertSame('foo@email.com', $email);
        $this->assertCollectionEquals($roles, $executedRoles);
        return true;
    })
    ->once();

// Refactored to
$this->mock(UpdateUser::class)
    ->shouldReceive('execute')
    ->withArgs(Matcher::make(
        $user,
        'foo@email.com',
        $roles
    ))
    ->once();
```

#### Partial match

[](#partial-match)

In some cases, we wish to check only a few arguments or call argument methods:

```
$this->mock(CreateUser::class)
    ->shouldReceive('execute')
    ->withArgs(function(UserDTO $data, Collection $executedRoles) use ($team, $roles) {
        $this->assertSame('foo@email.com', $data->email);
        $this->assertSame('password', $data->password);
        $this->assertIsModel($team, $data->team())
        $this->assertCollectionEquals($roles, $executedRoles);
        return true;
    })
    ->once();
```

We can use `Matcher::match` to define our assertions on `$data`:

```
$this->mock(CreateUser::class)
    ->shouldReceive('execute')
    ->withArgs(Matcher::make(
        Matcher::match('foo@email.com', fn(UserDTO $data) => $data->email)
            ->match('password', fn(UserDTO $data) => $data->password)
            ->match($team, fn(UserDTO $data) => $data->team()),
        $roles
    ))
    ->once();
```

In specific cases of object properties, we can use named parameters:

```
$this->mock(CreateUser::class)
    ->shouldReceive('execute')
    ->withArgs(Matcher::make(
        Matcher::match(email: 'foo@email.com', password: 'password')->match($team, fn(UserDTO $data) => $data->team()),
        $roles
    ))
    ->once();
```

We can also check object type:

```
$this->mock(CreateUser::class)
    ->shouldReceive('execute')
    ->withArgs(Matcher::make(
        Matcher::of(UserDTO::class)->properties(email: 'foo@email.com', password: 'password'),
        $roles
    ))
    ->once();
```

### ActionMock

[](#actionmock)

The trait `MocksActions` provides a `mockAction` method to simply mock an action. By convention, an action is a class with a `execute` method.

Under the hood, it uses `Mockery::mock`.

It allows to easily define your action's expectations. Instead of

```
$user = User::factory()->createOne();

$this->mock(DeleteUser::class)
    ->shouldReceive('execute')
    ->withArgs(function(User $executed) use ($user) {
        $this->assertIsModel($user, $executed);

        return true;
    })
    ->once();
```

you can write

```
$user = User::factory()->createOne();

$this->mockAction(DeleteUser::class)
   ->with($user);
```

You can also define the return value and capture it to use it in your test.

```
$this->mockAction(CreateUser::class)
    ->with(new UserData(email: 'john.doe@email.com', password: 'password'))
    ->returns(fn() => User::factory()->createOne())
    ->in($user);

$this->postJson('register', ['email' => 'john.doe@email.com', 'password' => 'password'])
    ->assertCreated()
    ->assertJson([
        'id' => $user->id,
        'name' => $user->name,
        'email' => $user->email,
    ]);
```

### Helpers

[](#helpers)

It can be necessary to capture the return value of a callback, for exemple in `returnUsing` of mocks.

```
$this->mock(CreateOrUpdateVersion::class)
    ->expects('execute')
    ->andReturnUsing(
        fn () => Version::factory()->for($package)->createOne()
    )
    ->once();

// I need created Version ! How do I do ?

```

In this case, we will use `capture` function:

```
$this->mock(CreateOrUpdateVersion::class)
    ->expects('execute')
    ->andReturnUsing(capture(
        $version,
        fn () => Version::factory()->for($package)->createOne()
    ))
    ->once();
```

Once the mock executed, `$version` is created and will contain the returned value of the callback.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Colin DeCarlo](https://github.com/colindecarlo) for the FormRequest isolation testing
- [Bastien Philippe](https://github.com/bastien-phi)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance87

Actively maintained with recent releases

Popularity29

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity74

Established project with proven stability

 Bus Factor1

Top contributor holds 61.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~53 days

Recently: every ~121 days

Total

28

Last Release

75d ago

Major Versions

1.3.0 → 2.0.02023-03-23

PHP version history (3 changes)1.0.0PHP ^8.1

2.4.0PHP ^8.2

2.11.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/206cfbf866a463f7e7d1e86946d59b82f4191b9c89f9981fb03eeb264d77af79?d=identicon)[SoyHuCe](/maintainers/SoyHuCe)

---

Top Contributors

[![bastien-phi](https://avatars.githubusercontent.com/u/10199039?v=4)](https://github.com/bastien-phi "bastien-phi (85 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (21 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (13 commits)")[![EdenMl](https://avatars.githubusercontent.com/u/70885551?v=4)](https://github.com/EdenMl "EdenMl (11 commits)")[![ElRochito](https://avatars.githubusercontent.com/u/1737307?v=4)](https://github.com/ElRochito "ElRochito (5 commits)")[![qanvo](https://avatars.githubusercontent.com/u/15672030?v=4)](https://github.com/qanvo "qanvo (2 commits)")[![tnajah59](https://avatars.githubusercontent.com/u/91531929?v=4)](https://github.com/tnajah59 "tnajah59 (1 commits)")

---

Tags

hacktoberfestlaravelteststestinglaravelsoyhuce

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/soyhuce-laravel-testing/health.svg)

```
[![Health](https://phpackages.com/badges/soyhuce-laravel-testing/health.svg)](https://phpackages.com/packages/soyhuce-laravel-testing)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)[timacdonald/log-fake

A drop in fake logger for testing with the Laravel framework.

4235.9M56](/packages/timacdonald-log-fake)[defstudio/pest-plugin-laravel-expectations

A plugin to add laravel tailored expectations to Pest

98548.9k4](/packages/defstudio-pest-plugin-laravel-expectations)[sti3bas/laravel-scout-array-driver

Array driver for Laravel Scout

971.5M3](/packages/sti3bas-laravel-scout-array-driver)[srlabs/laravel-testing-utilities

Helper utilities for testing Laravel Applications

1011.9k](/packages/srlabs-laravel-testing-utilities)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
