Skip to content

Commit

Permalink
Adds toMatchObject
Browse files Browse the repository at this point in the history
  • Loading branch information
nunomaduro committed Sep 15, 2020
1 parent 9b5f664 commit 4e184b2
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 3 deletions.
26 changes: 25 additions & 1 deletion src/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,20 @@ public function toHaveCount(int $count): Expectation

/**
* Asserts that the value contains the property $name.
*
* @param mixed $value
*/
public function toHaveProperty(string $name): Expectation
public function toHaveProperty(string $name, $value = null): Expectation
{
$this->toBeObject();

Assert::assertTrue(property_exists($this->value, $name));

if (func_num_args() > 1) {
/* @phpstan-ignore-next-line */
Assert::assertEquals($value, $this->value->{$name});
}

return $this;
}

Expand Down Expand Up @@ -460,6 +469,21 @@ public function toBeWritableFile(): Expectation
return $this;
}

/**
* Asserts that the value object matches a subset
* of the properties of an given object.
*
* @param array<string, mixed>|object $object
*/
public function toMatchObject($object): Expectation
{
foreach ((array) $object as $property => $value) {
$this->toHaveProperty($property, $value);
}

return $this;
}

/**
* Dynamically calls methods on the class without any arguments.
*
Expand Down
8 changes: 6 additions & 2 deletions tests/Expect/toHaveProperty.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

use PHPUnit\Framework\ExpectationFailedException;

$obj = new stdClass();
$obj->foo = 'bar';
$obj = new stdClass();
$obj->foo = 'bar';
$obj->fooNull = null;

test('pass', function () use ($obj) {
expect($obj)->toHaveProperty('foo');
expect($obj)->toHaveProperty('foo', 'bar');
expect($obj)->toHaveProperty('fooNull');
expect($obj)->toHaveProperty('fooNull', null);
});

test('failures', function () use ($obj) {
Expand Down
31 changes: 31 additions & 0 deletions tests/Expect/toMatchObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

use PHPUnit\Framework\ExpectationFailedException;

beforeEach(function () {
$this->user = (object) [
'id' => 1,
'name' => 'Nuno',
'email' => 'enunomaduro@gmail.com',
];
});

test('pass', function () {
expect($this->user)->toMatchObject([
'name' => 'Nuno',
'email' => 'enunomaduro@gmail.com',
]);
});

test('failures', function () {
expect($this->user)->toMatchObject([
'name' => 'Not the same name',
'email' => 'enunomaduro@gmail.com',
]);
})->throws(ExpectationFailedException::class);

test('not failures', function () {
expect($this->user)->not->toMatchObject([
'id' => 1,
]);
})->throws(ExpectationFailedException::class);

0 comments on commit 4e184b2

Please sign in to comment.