Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: assertStrictEquals #4611

Closed
BackEndTea opened this issue Feb 27, 2021 · 3 comments
Closed

Feature request: assertStrictEquals #4611

BackEndTea opened this issue Feb 27, 2021 · 3 comments
Labels
type/enhancement A new idea that should be implemented

Comments

@BackEndTea
Copy link
Contributor

The problem

Currently, phpunit has two ways of making sure variables are the same. assertEquals, and assertSame. Doing == and === checks respectively.

The problem comes when we are comparing objects. We can't always use assertSame, as we may not be able to provide the desired object beforehand. So we use assertEquals there. This however leads to problems in code where the properties of a class may not be a single type. Which can be due to union types, or just because of legacy code.

// https://3v4l.org/PpqMI
class Problem
{
    public function __construct(
        private bool|string $issue
    ) {}
}

var_dump(new Problem(true) == new Problem('There is a problem')); // true

The solution

I'd like to propose a new assertion: assertStrictEqals. Which would check every property to be exactly the same. on the two objects. This is already featured in other test frameworks like jest.

Is this something that could be implemented in PHPUnit? If so i'd be happy to provide a PR for it

@BackEndTea BackEndTea added the type/enhancement A new idea that should be implemented label Feb 27, 2021
@sebastianbergmann
Copy link
Owner

sebastianbergmann commented Feb 27, 2021

I do not think that a generic comparison of objects based on properties is useful and PHPUnit already has two ways for comparing objects: assertEquals() with custom comparators and assertObjectEquals().

@BackEndTea
Copy link
Contributor Author

Turns out i've misunderstood how assertEquals operates. And it basically does what i wanted it to do for object all along 😅 .

@webmozart
Copy link
Contributor

webmozart commented Apr 8, 2021

@BackEndTea IMO assertEquals() is very helpful for these kinds of comparisons, as its output is much more verbose when comparisons fail compared to assertObjectEquals(). If you want to continue using assertEquals() but with type safety, I recommend using my StrictPHPUnitExtension.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type/enhancement A new idea that should be implemented
Projects
None yet
Development

No branches or pull requests

3 participants