Skip to content

Commit f432874

Browse files
committed
add ArrayAssertions::assertSubset()
1 parent 6251c05 commit f432874

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ This will prevent any method name conflicts with core, your custom or other trai
2828
\Astrotomic\PhpunitAssertions\ArrayAssertions::assertIndexed(['foo', 'bar']);
2929
\Astrotomic\PhpunitAssertions\ArrayAssertions::assertAssociative(['foo' => 'bar']);
3030
\Astrotomic\PhpunitAssertions\ArrayAssertions::assertEquals(['foo', 'bar'], ['bar', 'foo']);
31+
\Astrotomic\PhpunitAssertions\ArrayAssertions::assertSubset(['foo' => 'bar'], ['baz' => 'foo', 'foo' => 'bar']);
3132
```
3233

3334
### Country

src/ArrayAssertions.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,14 @@ public static function assertEquals(array $expected, $actual): void
3838

3939
PHPUnit::assertEquals($expected, $actual);
4040
}
41+
42+
public static function assertSubset(array $expected, $actual): void
43+
{
44+
PHPUnit::assertIsArray($actual);
45+
46+
foreach($expected as $key => $value) {
47+
PHPUnit::assertArrayHasKey($key, $actual);
48+
PHPUnit::assertEquals($value, $actual[$key]);
49+
}
50+
}
4151
}

tests/ArrayAssertionsTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,19 @@ public static function it_can_validate_associative_array_equality(): void
5757

5858
ArrayAssertions::assertEquals($expected, $actual);
5959
}
60+
61+
/**
62+
* @test
63+
* @dataProvider hundredTimes
64+
*/
65+
public static function it_can_validate_associative_array_subset(): void
66+
{
67+
$array = self::randomArray(self::randomInt(5, 20), true);
68+
69+
$actual = $array;
70+
$expected = array_slice($array, 0, ceil(count($array) / self::randomInt(2, 4)), true);
71+
uksort($expected, fn (): int => self::randomInt() <=> self::randomInt());
72+
73+
ArrayAssertions::assertSubset($expected, $actual);
74+
}
6075
}

0 commit comments

Comments
 (0)