Skip to content

Commit 960cdf1

Browse files
author
Willem Stuursma
committed
Add a comparator to help with writing tests
1 parent 8c5649e commit 960cdf1

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/PHPUnit/Comparator.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false)
29+
{
30+
if ($expected->equals($actual)) {
31+
return;
32+
}
33+
34+
throw new ComparisonFailure(
35+
$expected,
36+
$actual,
37+
$this->formatEnum($expected),
38+
$this->formatEnum($actual),
39+
false,
40+
'Failed asserting that two Enums are equal.'
41+
);
42+
}
43+
44+
private function formatEnum(Enum $enum = null)
45+
{
46+
if ($enum === null) {
47+
return "null";
48+
}
49+
50+
return get_class($enum)."::{$enum->getKey()}()";
51+
}
52+
}

0 commit comments

Comments
 (0)