PHPackages                             bmarsaud/phpunit-snapshot-assertions - 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. bmarsaud/phpunit-snapshot-assertions

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

bmarsaud/phpunit-snapshot-assertions
====================================

Snapshot testing with PHPUnit

4.2.2(5y ago)021MITPHPPHP ^7.3

Since Dec 8Pushed 5y agoCompare

[ Source](https://github.com/bmarsaud/phpunit-snapshot-assertions)[ Packagist](https://packagist.org/packages/bmarsaud/phpunit-snapshot-assertions)[ Docs](https://github.com/bmarsaud/phpunit-snapshot-assertions)[ Fund](https://spatie.be/open-source/support-us)[ RSS](/packages/bmarsaud-phpunit-snapshot-assertions/feed)WikiDiscussions 4.2.2 Synced today

READMEChangelogDependencies (6)Versions (42)Used By (1)

Snapshot testing with PHPUnit
=============================

[](#snapshot-testing-with-phpunit)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4a07ffe9fa1cca352a46be72e924f76a6f9cf8dbe352afccc0737316e03d451b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f706870756e69742d736e617073686f742d617373657274696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/phpunit-snapshot-assertions)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![GitHub Tests Action Status](https://camo.githubusercontent.com/1428c59fa51920eb8683d4083f9afbdcf840f26fedb8d359560df2d38cd809b3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7370617469652f706870756e69742d736e617073686f742d617373657274696f6e732f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/spatie/phpunit-snapshot-assertions/actions?query=workflow%3Arun-tests+branch%3Amaster)[![Quality Score](https://camo.githubusercontent.com/d0f0cf8e335a3366af4b5a742644bf28dcee6f08e448b8ae3d89fa8a6fba11a8/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7370617469652f706870756e69742d736e617073686f742d617373657274696f6e732e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/spatie/phpunit-snapshot-assertions)[![StyleCI](https://camo.githubusercontent.com/75a665229439c780e726fee17721ac2b2ea1094342daca454aaeb4a6897e1d76/68747470733a2f2f7374796c6563692e696f2f7265706f732f37353932363138382f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/75926188)[![Total Downloads](https://camo.githubusercontent.com/e84efdecc49a6397d3bdc94283bb63ae64bd8c04b565630c955019fdd2631e9d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f706870756e69742d736e617073686f742d617373657274696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/phpunit-snapshot-assertions)

Why this fork ?
---------------

[](#why-this-fork-)

The purpose of this fork is to make the `spatie/phpunit-snapshot-assertions` package compatible with PHP 7.3.

The compatibility is ensured using [Rector](https://github.com/rectorphp/rector).

Note that he only version currently available is the `4.2.2`.

A more durable and reliable way would be to use a GitHub action applying Rector on each tag pushed on the original repository.

Description
-----------

[](#description)

> Snapshot testing is a way to test without writing actual test cases

```
use Spatie\Snapshots\MatchesSnapshots;

class OrderTest
{
    use MatchesSnapshots;

    public function test_it_casts_to_json()
    {
        $order = new Order(1);

        $this->assertMatchesJsonSnapshot($order->toJson());
    }
}
```

On the first run, the test runner will create a new snapshot.

```
> ./vendor/bin/phpunit

There was 1 incomplete test:

1) OrderTest::test_it_casts_to_json
Snapshot created for OrderTest__test_it_casts_to_json__1

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Incomplete: 1.

```

On subsequent runs, the test will pass as long as the snapshot doesn't change.

```
> ./vendor/bin/phpunit

OK (1 test, 1 assertion)

```

If there's a regression, the test will fail!

```
$orderId = new Order(2); // Regression! Was `1`
```

```
> ./vendor/bin/phpunit

1) OrderTest::test_it_casts_to_json
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
Failed asserting that '{"id":2}' matches JSON string "{
    "id": 1
}

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

```

Support us
----------

[](#support-us)

Learn how to create a package like this one, by watching our premium video course:

[![Laravel Package training](https://camo.githubusercontent.com/4c7f3720a29525e627f6004ee367e55def510e45d18e6bc974725812fa5cf257/68747470733a2f2f7370617469652e62652f6769746875622f7061636b6167652d747261696e696e672e6a7067)](https://laravelpackage.training)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

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

[](#installation)

You can install the package via composer:

```
composer require --dev spatie/phpunit-snapshot-assertions
```

Usage
-----

[](#usage)

To make snapshot assertions, use the `Spatie\Snapshots\MatchesSnapshots` trait in your test case class. This adds a set of assertion methods to the class:

- `assertMatchesSnapshot($actual)`
- `assertMatchesFileHashSnapshot($actual)`
- `assertMatchesFileSnapshot($actual)`
- `assertMatchesHtmlSnapshot($actual)`
- `assertMatchesJsonSnapshot($actual)`
- `assertMatchesObjectSnapshot($actual)`
- `assertMatchesTextSnapshot($actual)`
- `assertMatchesXmlSnapshot($actual)`
- `assertMatchesYamlSnapshot($actual)`

### Snapshot Testing 101

[](#snapshot-testing-101)

Let's do a snapshot assertion for a simple string, "foo".

```
public function test_it_is_foo() {
    $this->assertMatchesSnapshot('foo');
}
```

The first time the assertion runs, it doesn't have a snapshot to compare the string with. The test runner generates a new snapshot and marks the test as incomplete.

```
> ./vendor/bin/phpunit

There was 1 incomplete test:

1) ExampleTest::test_it_matches_a_string
Snapshot created for ExampleTest__test_it_matches_a_string__1

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Incomplete: 1.

```

Snapshot ids are generated based on the test and testcase's names. Basic snapshots return a plain text or YAML representation of the actual value.

```
foo
```

Let's rerun the test. The test runner will see that there's already a snapshot for the assertion and do a comparison.

```
> ./vendor/bin/phpunit

OK (1 test, 1 assertion)

```

If we change actual value to "bar", the test will fail because the snapshot still returns "foo".

```
public function test_it_is_foo() {
    $this->assertMatchesSnapshot('bar');
}
```

```
> ./vendor/bin/phpunit

1) ExampleTest::test_it_matches_a_string
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'foo'
+'bar'

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

```

When we expect a changed value, we need to tell the test runner to update the existing snapshots instead of failing the test. This is possible by adding a`-d --update-snapshots` flag to the `phpunit` command.

```
> ./vendor/bin/phpunit -d --update-snapshots

OK (1 test, 1 assertion)

```

As a result, our snapshot file returns "bar" instead of "foo".

```
bar
```

### File snapshots

[](#file-snapshots)

The `MatchesSnapshots` trait offers two ways to assert that a file is identical to the snapshot that was made the first time the test was run:

The `assertMatchesFileHashSnapshot($filePath)` assertion asserts that the hash of the file passed into the function and the hash saved in the snapshot match. This assertion is fast and uses very little disk space. The downside of this assertion is that there is no easy way to see how the two files differ if the test fails.

The `assertMatchesFileSnapshot($filePath)` assertion works almost the same way as the file hash assertion, except that it actually saves the whole file in the snapshots directory. If the assertion fails, it places the failed file next to the snapshot file so they can easily be manually compared. The persisted failed file is automatically deleted when the test passes. This assertion is most useful when working with binary files that should be manually compared like images or pdfs.

### Customizing Snapshot Ids and Directories

[](#customizing-snapshot-ids-and-directories)

Snapshot ids are generated via the `getSnapshotId` method on the `MatchesSnapshot` trait. Override the method to customize the id. By default, a snapshot id exists of the test name, the test case name and an incrementing value, e.g. `Test__my_test_case__1`.

#### Example: Replacing the `__` Delimiter With `--`

[](#example-replacing-the-__-delimiter-with---)

```
protected function getSnapshotId(): string
{
    return (new ReflectionClass($this))->getShortName().'--'.
        $this->getName().'--'.
        $this->snapshotIncrementor;
}
```

By default, snapshots are stored in a `__snapshots__` directory relative to the test class. This can be changed by overriding the `getSnapshotDirectory` method.

#### Example: Renaming the `__snapshots__` directory to `snapshots`

[](#example-renaming-the-__snapshots__-directory-to-snapshots)

```
protected function getSnapshotDirectory(): string
{
    return dirname((new ReflectionClass($this))->getFileName()).
        DIRECTORY_SEPARATOR.
        'snapshots';
}
```

### Using specific Drivers

[](#using-specific-drivers)

The driver used to serialize the data can be specificied as second argument of the `assertMatchesSnapshot` method, so you can pick one that better suits your needs:

```
use Spatie\Snapshots\Drivers\JsonDriver;
use Spatie\Snapshots\MatchesSnapshots;

class OrderTest
{
    use MatchesSnapshots;

    public function test_snapshot_with_json_driver()
    {
        $order = new Order(1);

        $this->assertMatchesSnapshot($order->toJson(), new JsonDriver());
    }
}
```

### Writing Custom Drivers

[](#writing-custom-drivers)

Drivers ensure that different types of data can be serialized and matched in their own way. A driver is a class that implements the `Spatie\Snapshots\Driver` interface, which requires three method implementations: `serialize`, `extension` and `match`.

Let's take a quick quick look at the `JsonDriver`.

```
namespace Spatie\Snapshots\Drivers;

use PHPUnit\Framework\Assert;
use Spatie\Snapshots\Driver;
use Spatie\Snapshots\Exceptions\CantBeSerialized;

class JsonDriver implements Driver
{
    public function serialize($data): string
    {
        if (! is_string($data)) {
            throw new CantBeSerialized('Only strings can be serialized to json');
        }

        return json_encode(json_decode($data), JSON_PRETTY_PRINT).PHP_EOL;
    }

    public function extension(): string
    {
        return 'json';
    }

    public function match($expected, $actual)
    {
        Assert::assertJsonStringEqualsJsonString($actual, $expected);
    }
}
```

- The `serialize` method returns a string which will be written to the snapshot file. In the `JsonDriver`, we'll decode and re-encode the json string to ensure the snapshot has pretty printing.
- We want to save json snapshots as json files, so we'll use `json` as their file extension.
- When matching the expected data with the actual data, we want to use PHPUnit's built in json assertions, so we'll call the specific `assertJsonStringEqualsJsonString` method.

Drivers can be used by passing them as `assertMatchesSnapshot`'s second argument.

```
$this->assertMatchesSnapshot($something->toYaml(), new MyYamlDriver());
```

### Usage in CI

[](#usage-in-ci)

When running your tests in Continuous Integration you would possibly want to disable the creation of snapshots.

By using the `--without-creating-snapshots` parameter, PHPUnit will fail if the snapshots don't exist.

```
> ./vendor/bin/phpunit -d --without-creating-snapshots

1) ExampleTest::test_it_matches_a_string
Snapshot "ExampleTest__test_it_matches_a_string__1.txt" does not exist.
You can automatically create it by removing `-d --no-create-snapshots` of PHPUnit's CLI arguments.
```

### A note for Windows users

[](#a-note-for-windows-users)

Windows users should configure their line endings in `.gitattributes`.

```
tests/**/__snapshots__/** text eol=lf
```

Changelog
---------

[](#changelog)

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

Testing
-------

[](#testing)

```
composer test
```

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

[](#contributing)

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

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Sebastian De Deyne](https://github.com/sebastiandedeyne)
- [Alex Vanderbist](https://github.com/alexvanderbist)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

30

—

LowBetter than 65% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity2

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~37 days

Recently: every ~46 days

Total

39

Last Release

2037d ago

Major Versions

0.4.1 → 1.0.02017-05-29

1.4.1 → 2.0.02019-01-29

1.4.2 → 2.1.32019-08-07

2.2.1 → 3.0.02019-11-22

3.1.1 → 4.0.02020-02-11

PHP version history (5 changes)0.1.0PHP ^7.0

2.0.0PHP ^7.1

2.1.0PHP ^7.2

3.1.0PHP ^7.4

4.2.2PHP ^7.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/6af64f6dbe6fa99b725db78995e1b8baaae12f45583fe6d4f399c58fe50896b3?d=identicon)[bmarsaud](/maintainers/bmarsaud)

---

Top Contributors

[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (115 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (63 commits)")[![SjorsO](https://avatars.githubusercontent.com/u/7202674?v=4)](https://github.com/SjorsO "SjorsO (18 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (11 commits)")[![mathieutu](https://avatars.githubusercontent.com/u/11351322?v=4)](https://github.com/mathieutu "mathieutu (11 commits)")[![vhenzl](https://avatars.githubusercontent.com/u/243381?v=4)](https://github.com/vhenzl "vhenzl (6 commits)")[![nclavaud](https://avatars.githubusercontent.com/u/1181770?v=4)](https://github.com/nclavaud "nclavaud (5 commits)")[![Gummibeer](https://avatars.githubusercontent.com/u/6187884?v=4)](https://github.com/Gummibeer "Gummibeer (5 commits)")[![bmarsaud](https://avatars.githubusercontent.com/u/2720587?v=4)](https://github.com/bmarsaud "bmarsaud (5 commits)")[![kojirock5260](https://avatars.githubusercontent.com/u/6925110?v=4)](https://github.com/kojirock5260 "kojirock5260 (3 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (3 commits)")[![Kanti](https://avatars.githubusercontent.com/u/471387?v=4)](https://github.com/Kanti "Kanti (3 commits)")[![bramdevries](https://avatars.githubusercontent.com/u/1002245?v=4)](https://github.com/bramdevries "bramdevries (2 commits)")[![ianrodrigues](https://avatars.githubusercontent.com/u/5269377?v=4)](https://github.com/ianrodrigues "ianrodrigues (2 commits)")[![romainnorberg](https://avatars.githubusercontent.com/u/7681951?v=4)](https://github.com/romainnorberg "romainnorberg (2 commits)")[![jakubkulhan](https://avatars.githubusercontent.com/u/95001?v=4)](https://github.com/jakubkulhan "jakubkulhan (2 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (2 commits)")[![Korri](https://avatars.githubusercontent.com/u/130747?v=4)](https://github.com/Korri "Korri (1 commits)")[![evilebottnawi](https://avatars.githubusercontent.com/u/23334705?v=4)](https://github.com/evilebottnawi "evilebottnawi (1 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (1 commits)")

---

Tags

php73phpunitphpunit-assertionsspatietestingphpunitsnapshotassertphpunit-snapshot-assertionsphp73

###  Code Quality

TestsPHPUnit

Static AnalysisRector

### Embed Badge

![Health badge](/badges/bmarsaud-phpunit-snapshot-assertions/health.svg)

```
[![Health](https://phpackages.com/badges/bmarsaud-phpunit-snapshot-assertions/health.svg)](https://phpackages.com/packages/bmarsaud-phpunit-snapshot-assertions)
```

###  Alternatives

[spatie/phpunit-snapshot-assertions

Snapshot testing with PHPUnit

69417.9M511](/packages/spatie-phpunit-snapshot-assertions)[brianium/paratest

Parallel testing for PHP

2.5k118.8M753](/packages/brianium-paratest)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.0k](/packages/orchestra-testbench)[yoast/phpunit-polyfills

Set of polyfills for changed PHPUnit functionality to allow for creating PHPUnit cross-version compatible tests

18338.5M839](/packages/yoast-phpunit-polyfills)[ta-tikoma/phpunit-architecture-test

Methods for testing application architecture

10745.9M13](/packages/ta-tikoma-phpunit-architecture-test)[matthiasnoback/symfony-config-test

Library for testing user classes related to the Symfony Config Component

1679.8M395](/packages/matthiasnoback-symfony-config-test)

PHPackages © 2026

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