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
Assert that arrays (or objects) are equal while excluding certain keys (or properties) #5108
Comments
My suggestion would be to implement |
This can be done with a custom comparator, if I understand the issue correctly. |
@lolli42 You are correct. I am still undecided whether or not I want to implement this or not. |
I have quite a complex immutable value object representing a time interval (like So I thought: let's add a private property that acts as a cache for these values (as they can never change for a given instance of the object), and they'll be computed only once the first time we need them. Like : private bool $isEmpty;
public function isEmpty(): bool
{
return $this->isEmpty ??=
null !== $this->start && null !== $this->end && $this->start->equals($this->end);
} What I did not expect was that now most of my unit tests are broken, because we compare objects (and array of objects, and objects containing arrays of objects,... you get the gist) quite a lot, and now sometimes these cache properties will be set, and sometimes they wont (depending on whether or not the method was called at least once before the comparison). Which is then seen as a difference by Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
0 => Gammadia\DateTimeExtra\LocalDateTimeInterval Object (
'start' => Brick\DateTime\LocalDateTime Object (...)
'end' => Brick\DateTime\LocalDateTime Object (...)
- 'isEmpty' => false
)
1 => 1
)
)
) @sebastianbergmann Is there a way to tell PHPUnit to globally ignore these cache-related private properties when doing comparisons (so not by registering some custom comparator in each test or changing the assert method) ? Something like the Or is there another way to have this cache without the comparison issue that I'm not seeing ? |
No, you "only" have the two options PHPUnit provides for this so far: registering a custom comparator or using |
Thanks for your answer. I went the |
Some object may have properties with unpredictable values, like random UUID, and you want to compare the predictable ones.
In Java, with AssertJ it’s possible with:
assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected)
.Maybe a signature like
assertEqualsIgnoringFields($expected, $actual, string ...$fields)
The text was updated successfully, but these errors were encountered: