Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Creational/Singleton/Singleton.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use LogicException;

final class Singleton
class Singleton
{
private static ?Singleton $instance = null;

Expand All @@ -26,7 +26,7 @@ private function __construct()
private function __clone(): void
{
}

public function __sleep(): array
{
throw new LogicException('Cannot serialize a singleton.');
Expand Down
75 changes: 43 additions & 32 deletions tests/Creational/Singleton/SingletonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,46 @@

final class SingletonTest extends TestCase
{
public function testShouldBeTheSameInstanceForTwoObjets(): void
{
$firstInstance = Singleton::getInstance();
$secondInstance = SingleTon::getInstance();

$this->assertSame($firstInstance, $secondInstance);
}

public function testShouldThrowErrorWhenTryToCreateInstance(): void
{
$this->expectException(Error::class);

$instance = new Singleton();
}

public function testShouldThrowErrorWhenTryToClone(): void
{
$this->expectException(Error::class);

$instance = Singleton::getInstance();
$clone = clone $instance;
}

public function testShouldThrowExceptionWhenTryToSerialize(): void
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot serialize a singleton.');

$instance = Singleton::getInstance();
$serialize = serialize($instance);
}
}
public function testShouldBeTheSameInstanceForTwoObjets(): void
{
$firstInstance = Singleton::getInstance();
$secondInstance = SingleTon::getInstance();

$this->assertSame($firstInstance, $secondInstance);
}

public function testShouldThrowErrorWhenTryToCreateInstance(): void
{
$this->expectException(Error::class);

$instance = new Singleton();
}

public function testShouldThrowErrorWhenTryToClone(): void
{
$this->expectException(Error::class);

$instance = Singleton::getInstance();
$clone = clone $instance;
}

public function testShouldThrowExceptionWhenTryToSerialize(): void
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Cannot serialize a singleton.');

$instance = Singleton::getInstance();
$serialize = serialize($instance);
}

public function testShouldThrowExceptionWhenTryToUnserialize(): void
{
$this->expectException(LogicException::class);
//$this->expectExceptionMessage('Cannot unserialize a singleton.');

$instance = Singleton::getInstance();
$serialize = serialize($instance); // vai cair na exceção do serialize

$unserialize = unserialize($serialize); // não vai chegar aqui
}
}