diff --git a/src/ComparisonFailure.php b/src/ComparisonFailure.php index b5c2ac2d..11e7ba66 100644 --- a/src/ComparisonFailure.php +++ b/src/ComparisonFailure.php @@ -65,4 +65,28 @@ public function toString(): string { return $this->getMessage() . $this->getDiff(); } + + /** + * Serialises all parts of the comparison failure, apart from the stacktrace which might contain references to + * objects which cannot be serialised. + */ + public function __serialize(): array + { + return [ + $this->expected, + $this->actual, + $this->expectedAsString, + $this->actualAsString, + ]; + } + + public function __unserialize(array $data): void + { + [ + $this->expected, + $this->actual, + $this->expectedAsString, + $this->actualAsString, + ] = $data; + } } diff --git a/tests/ComparisonFailureTest.php b/tests/ComparisonFailureTest.php index fca3b2a7..c3664d5b 100644 --- a/tests/ComparisonFailureTest.php +++ b/tests/ComparisonFailureTest.php @@ -55,4 +55,31 @@ public function testDiffNotPossible(): void $this->assertSame('', $failure->getDiff()); $this->assertSame('test', $failure->toString()); } + + public function testSerialize(): void + { + $failure = new ComparisonFailure(true, false, 'true', 'false', 'test'); + $serialised = $failure->__serialize(); + $this->assertSame([true, false, 'true', 'false'], $serialised); + } + + public function testUnserialize(): void + { + $failure = new ComparisonFailure(true, false, 'true', 'false', 'test'); + $failure->__unserialize([true, false, 'true', 'false']); + + $this->assertTrue($failure->getExpected()); + $this->assertFalse($failure->getActual()); + $this->assertSame('true', $failure->getExpectedAsString()); + $this->assertSame('false', $failure->getActualAsString()); + $diff = ' +--- Expected ++++ Actual +@@ @@ +-true ++false +'; + $this->assertSame($diff, $failure->getDiff()); + $this->assertSame('test' . $diff, $failure->toString()); + } }