Enables type-safe comparisons of objects in PHPUnit.

Overview

Strict PHPUnit

Enables type-safe comparisons of objects in PHPUnit.

Problem

PHPUnit has a very powerful comparison system that helps you comparing objects with expected values:

class ValueObject
{
    public ?string $property;
    
    public function __construct(?string $property)
    {
        $this->property = $property;
    }
}

$actual = new ValueObject('foo!');

self::assertEquals(new ValueObject('foo'), $actual);
// => fails with a very helpful error message

This comparison system will give you a meaningful exception that guides you precisely to the problem that caused the assertion to fail. Strings are furthermore diffed so that you see exactly which character of the string causes a mismatch.

PHPUnit compares each scalar property of an object with relaxed types. It is a little more intelligent than using just == under the hood, but still that will not always provide the results you want:

var_dump('Hi' == true);
// => true

self::assertEquals(new ValueObject('Hi'), new ValueObject(true));
// => fails

var_dump('' == null);
// => true

self::assertEquals(new ValueObject(''), new ValueObject(null));
// => succeeds

Solution

This extension enables a comparator for scalar values that fights this problem. With this extension, whenever PHPUnit finds a scalar value during assertEquals() (even recursively within objects or arrays), it will compare the value with ===.

Objects are still not checked for identity, hence you can still construct example objects to compare against.

Error messages stay meaningful.

self::assertEquals(new ValueObject(''), new ValueObject(null));
// => fails with a meaningful error

self::assertEquals(new ValueObject('foo!'), new ValueObject('foo'));
// => fails with a meaningful error

self::assertEquals(new ValueObject('foo!'), new ValueObject('foo!'));
// => succeeds

Installation

The extension can be installed with Composer:

$ composer require --dev webmozarts/strict-phpunit

Add the extension to your phpunit.xml.dist file to enable it:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd">
    <!-- ... -->
    
    <extensions>
        <extension class="Webmozarts\StrictPHPUnit\StrictPHPUnitExtension"/>
    </extensions>
    
    <!-- ... -->
</phpunit>

Authors

Contribute

Contributions to the package are always welcome!

Note that this repository is a subtree-split of a monorepo and hence read only. PRs will be ported to the (internal) monorepo.

License

All contents of this package are licensed under the MIT license.

You might also like...
Set of polyfills for changed PHPUnit functionality to allow for creating PHPUnit cross-version compatible tests

PHPUnit Polyfills Set of polyfills for changed PHPUnit functionality to allow for creating PHPUnit cross-version compatible tests. Requirements Instal

Satisfy the Type APIs for the WordPress schema when running PHPUnit tests

Satisfy the Type APIs for the WordPress schema when running PHPUnit tests

Collection of value objects that represent the types of the PHP type system

sebastian/type Collection of value objects that represent the types of the PHP type system. Installation You can add this library as a local, per-proj

PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects.

πŸ“’ Yell PHP package to make your objects strict and throw exception when you try to access or set some undefined property in your objects. Requirement

Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.DeepEqual().

Deeper Deeper is a easy way to compare if 2 objects is equal based on values in these objects. This library is heavily inspired in Golang's reflect.De

Generate Data Transfer Objects directly from JSON objects
Generate Data Transfer Objects directly from JSON objects

Json 2 DTO Spatie's Data Transfer Object library is awesome, but typing out DTOs can quickly become a chore. Inspired by Json2Typescript style tools,

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

Super Simple DTO Creating data transfer objects with the power of php objects. No php attributes, no reflection api, and no other under the hook work.

☁️ Nextcloud server, a safe home for all your data
☁️ Nextcloud server, a safe home for all your data

Nextcloud Server ☁ A safe home for all your data. Why is this so awesome? 🀩 πŸ“ Access your Data You can store your files, contacts, calendars and mor

The Current US Version of PHP-Nuke Evolution Xtreme v3.0.1b-beta often known as Nuke-Evolution Xtreme. This is a hardened version of PHP-Nuke and is secure and safe. We are currently porting Xtreme over to PHP 8.0.3
The Current US Version of PHP-Nuke Evolution Xtreme v3.0.1b-beta often known as Nuke-Evolution Xtreme. This is a hardened version of PHP-Nuke and is secure and safe. We are currently porting Xtreme over to PHP 8.0.3

2021 Nightly Builds Repository PHP-Nuke Evolution Xtreme Developers TheGhost - Ernest Allen Buffington (Lead Developer) SeaBeast08 - Sebastian Scott B

Make your PHP arrays sweet'n'safe

Mess We face a few problems in our PHP projects Illogical type casting (PHP's native implementation is way too "smart") Pointless casts like array =

Tailwind plugin to generate purge-safe.txt files
Tailwind plugin to generate purge-safe.txt files

Tailwind plugin to generate safelist.txt files With tailwind-safelist-generator, you can generate a safelist.txt file for your theme based on a set of

Staggered import of large and very large MySQL Dumps even through the web servers with hard runtime limit and those in safe mode.

Staggered import of large and very large MySQL Dumps (like phpMyAdmin dumps) even through the web servers with hard runtime limit and those in safe mode. | Persian Translation Version

HTML sanitizer, written in PHP, aiming to provide XSS-safe markup based on explicitly allowed tags, attributes and values.

TYPO3 HTML Sanitizer ℹ️ Common safe HTML tags & attributes as given in \TYPO3\HtmlSanitizer\Builder\CommonBuilder still might be adjusted, extended or

A simple, safe magic login link generator for Laravel

Laravel Passwordless Login A simple, safe magic login link generator for Laravel This package provides a temporary signed route that logs in a user. W

Obfuscate your data by generating reversible, non-sequential, URL-safe identifiers.

Laravel Hashid Laravel Hashid provides a unified API across various drivers such as Base62, Base64, Hashids and Optimus, with support for multiple con

Html-sanitizer - The HtmlSanitizer component provides an object-oriented API to sanitize untrusted HTML input for safe insertion into a document's DOM.

HtmlSanitizer Component The HtmlSanitizer component provides an object-oriented API to sanitize untrusted HTML input for safe insertion into a documen

LaravelFly is a safe solution to speeds up new or old Laravel 5.5+ projects, with preloading and coroutine, while without data pollution or memory leak

Would you like php 7.4 Preloading? Would you like php coroutine? Today you can use them with Laravel because of Swoole. With LaravalFly, Laravel will

Owner
Webmozarts GmbH
Web and App Development in Vienna, Budapest and Barcelona
Webmozarts GmbH
Multibyte strings as objects

Opis String Multibyte strings Opis String is a tiny library that allows you to work with multibyte encoded strings in an object-oriented manner. The l

Opis 58 Oct 6, 2022
Identifies objects in an image using Machine Learning.

laravel-object-detection This package identifies objects in an image using Machine Learning, TensorFlow and the coco-ssd model. Installation You can i

Fredrik 91 Oct 23, 2022
Mockery - Designed as a drop in alternative to PHPUnit's phpunit-mock-objects library

Mockery Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its c

Mockery 10.3k Jan 1, 2023
YCOM Impersonate. Login as selected YCOM user πŸ§™β€β™‚οΈin frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
A simple, type-safe, zero dependency port of the javascript fetch WebApi for PHP.

A simple, type-safe, zero dependency port of the javascript fetch WebApi for PHP.

Matias Navarro Carter 105 Jan 4, 2023
PCRE wrapping library that offers type-safe preg_* replacements.

composer/pcre PCRE wrapping library that offers type-safe preg_* replacements. If you are using a modern PHP version you are probably better off using

Composer 308 Dec 30, 2022
A collection of type-safe functional data structures

lamphpda A collection of type-safe functional data structures Aim The aim of this library is to provide a collection of functional data structures in

Marco Perone 99 Nov 11, 2022
Magento 2 Module that adds Donation Product Type. Enables the customer to add a donation (product) of a preferred amount to the cart.

Magento 2 Module Experius DonationProduct (RC1.0) Demo website: https://donationproduct.experius.nl Magento Marketplace: https://marketplace.magento.c

Experius 23 Apr 1, 2022
Provides generic data providers for use with phpunit/phpunit.

data-provider Installation Run composer require --dev ergebnis/data-provider Usage This package provides the following generic data providers: Ergebni

null 25 Jan 2, 2023
Qase-phpunit - Qase TMS PHPUnit reporter.

Qase TMS PHPUnit reporter Publish results simple and easy. How to integrate composer require qase/phpunit-reporter Example of usage The PHPUnit report

Qase TMS 6 Nov 24, 2022