Skip to content

Commit ab5bb58

Browse files
authored
Add a comparator to help with writing tests (#90)
Add a comparator to help with writing tests
2 parents 758bc39 + 3c33ff2 commit ab5bb58

File tree

3 files changed

+58
-1
lines changed

3 files changed

+58
-1
lines changed

phpunit.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
processIsolation="false"
1212
stopOnFailure="false"
1313
syntaxCheck="false"
14-
bootstrap="./vendor/autoload.php">
14+
bootstrap="./tests/bootstrap.php">
1515
<testsuites>
1616
<testsuite name="PHP Enum Test Suite">
1717
<directory suffix=".php">./tests</directory>

src/PHPUnit/Comparator.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
3+
namespace MyCLabs\Enum\PHPUnit;
4+
5+
use MyCLabs\Enum\Enum;
6+
use SebastianBergmann\Comparator\ComparisonFailure;
7+
8+
/**
9+
* Use this Comparator to get nice output when using PHPUnit assertEquals() with Enums.
10+
*
11+
* Add this to your PHPUnit bootstrap PHP file:
12+
*
13+
* \SebastianBergmann\Comparator\Factory::getInstance()->register(new \MyCLabs\Enum\PHPUnit\Comparator());
14+
*/
15+
final class Comparator extends \SebastianBergmann\Comparator\Comparator
16+
{
17+
public function accepts($expected, $actual)
18+
{
19+
return $expected instanceof Enum && (
20+
$actual instanceof Enum || $actual === null
21+
);
22+
}
23+
24+
/**
25+
* @param Enum $expected
26+
* @param Enum|null $actual
27+
*
28+
* @return void
29+
*/
30+
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
31+
{
32+
if ($expected->equals($actual)) {
33+
return;
34+
}
35+
36+
throw new ComparisonFailure(
37+
$expected,
38+
$actual,
39+
$this->formatEnum($expected),
40+
$this->formatEnum($actual),
41+
false,
42+
'Failed asserting that two Enums are equal.'
43+
);
44+
}
45+
46+
private function formatEnum(Enum $enum = null)
47+
{
48+
if ($enum === null) {
49+
return "null";
50+
}
51+
52+
return get_class($enum)."::{$enum->getKey()}()";
53+
}
54+
}

tests/bootstrap.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<?php
2+
3+
\SebastianBergmann\Comparator\Factory::getInstance()->register(new \MyCLabs\Enum\PHPUnit\Comparator());

0 commit comments

Comments
 (0)