Skip to content

Commit

Permalink
use container instead of a singleton for UnitMockRegistry
Browse files Browse the repository at this point in the history
  • Loading branch information
Mulkave committed Oct 24, 2021
1 parent 8c64401 commit b041650
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
11 changes: 8 additions & 3 deletions src/Testing/MockMe.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,23 @@

namespace Lucid\Testing;

use Mockery\Mock;

trait MockMe
{
public static function mock(array $constructorExpectations = []): UnitMock
{
$unit = static::class;

if (UnitMockRegistry::has($unit)) {
$mock = UnitMockRegistry::get($unit);
/** @var UnitMockRegistry $registry */
$registry = app(UnitMockRegistry::class);

if ($registry->has($unit)) {
$mock = $registry->get($unit);
$mock->setConstructorExpectations($constructorExpectations);
} else {
$mock = new UnitMock($unit, $constructorExpectations);
UnitMockRegistry::register($unit, $mock);
$registry->register($unit, $mock);
}

return $mock;
Expand Down
30 changes: 22 additions & 8 deletions src/Testing/UnitMockRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,36 @@ class UnitMockRegistry
/**
* @var array
*/
private static $mocks = [];
private $mocks = [];

public static function has(string $unit): bool
public function __construct()
{
return isset(self::$mocks[$unit]);
// there should only be one instance of the registry,
// so we register ourselves onto the application to be reused.
// this is necessary in order to have a clean registry at the beginning of each test method run,
// otherwise, with a singleton mocks will be carried on across test runs within the same class.
app()->instance(static::class, $this);
}

public static function get(string $unit): ?UnitMock
public function has(string $unit): bool
{
if (!self::has($unit)) return null;
return isset($this->mocks[$unit]);
}

public function get(string $unit): ?UnitMock
{
if (!$this->has($unit)) return null;

return self::$mocks[$unit];
return $this->mocks[$unit];
}

public function register(string $unit, UnitMock $mock)
{
$this->mocks[$unit] = $mock;
}

public static function register(string $unit, UnitMock $mock)
public function count()
{
self::$mocks[$unit] = $mock;
return count($this->mocks);
}
}

0 comments on commit b041650

Please sign in to comment.