Skip to content

Commit

Permalink
Fix: Add tests for Container (#727)
Browse files Browse the repository at this point in the history
  • Loading branch information
localheinz committed Sep 5, 2023
1 parent 4560966 commit 75318aa
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
56 changes: 56 additions & 0 deletions test/Faker/Extension/ContainerTest.php
Expand Up @@ -5,8 +5,10 @@
namespace Faker\Test\Extension;

use Faker\Container\Container;
use Faker\Container\ContainerException;
use Faker\Core\File;
use Faker\Extension\Extension;
use Faker\Test;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
Expand All @@ -16,13 +18,31 @@
*/
final class ContainerTest extends TestCase
{
public function testHasThrowsInvalidArgumentExceptionWhenIdentifierIsNotAString(): void
{
$container = new Container([]);

$this->expectException(\InvalidArgumentException::class);

$container->has(false);
}

public function testHasReturnsFalseWhenContainerDoesNotHaveDefinitionForService(): void
{
$container = new Container([]);

self::assertFalse($container->has('foo'));
}

public function testGetThrowsInvalidArgumentExceptionWhenIdentifierIsNotAString(): void
{
$container = new Container([]);

$this->expectException(\InvalidArgumentException::class);

$container->get(false);
}

public function testGetThrowsNotFoundExceptionWhenContainerDoesNotHaveDefinitionForService(): void
{
$container = new Container([]);
Expand All @@ -43,6 +63,42 @@ public function testGetFromString(): void
self::assertInstanceOf(File::class, $object);
}

public function testGetThrowsRuntimeExceptionWhenServiceCouldNotBeResolvedFromCallable(): void
{
$id = 'foo';

$container = new Container([
$id => static function (): void {
throw new \RuntimeException();
},
]);

$this->expectException(ContainerException::class);
$this->expectExceptionMessage(sprintf(
'Error while invoking callable for "%s"',
$id,
));

$container->get($id);
}

public function testGetThrowsRuntimeExceptionWhenServiceCouldNotBeResolvedFromClass(): void
{
$id = 'foo';

$container = new Container([
$id => Test\Fixture\Container\UnconstructableClass::class,
]);

$this->expectException(ContainerException::class);
$this->expectExceptionMessage(sprintf(
'Could not instantiate class "%s"',
$id,
));

$container->get($id);
}

/**
* @dataProvider provideDefinitionThatDoesNotResolveToExtension
*/
Expand Down
15 changes: 15 additions & 0 deletions test/Fixture/Container/UnconstructableClass.php
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Faker\Test\Fixture\Container;

use Faker\Extension;

final class UnconstructableClass implements Extension\Extension
{
public function __construct()
{
throw new \RuntimeException('Sorry, not sorry');
}
}

0 comments on commit 75318aa

Please sign in to comment.