Skip to content

Commit b041650

Browse files
committed
use container instead of a singleton for UnitMockRegistry
1 parent 8c64401 commit b041650

File tree

2 files changed

+30
-11
lines changed

2 files changed

+30
-11
lines changed

src/Testing/MockMe.php

+8-3
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,23 @@
22

33
namespace Lucid\Testing;
44

5+
use Mockery\Mock;
6+
57
trait MockMe
68
{
79
public static function mock(array $constructorExpectations = []): UnitMock
810
{
911
$unit = static::class;
1012

11-
if (UnitMockRegistry::has($unit)) {
12-
$mock = UnitMockRegistry::get($unit);
13+
/** @var UnitMockRegistry $registry */
14+
$registry = app(UnitMockRegistry::class);
15+
16+
if ($registry->has($unit)) {
17+
$mock = $registry->get($unit);
1318
$mock->setConstructorExpectations($constructorExpectations);
1419
} else {
1520
$mock = new UnitMock($unit, $constructorExpectations);
16-
UnitMockRegistry::register($unit, $mock);
21+
$registry->register($unit, $mock);
1722
}
1823

1924
return $mock;

src/Testing/UnitMockRegistry.php

+22-8
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,36 @@ class UnitMockRegistry
77
/**
88
* @var array
99
*/
10-
private static $mocks = [];
10+
private $mocks = [];
1111

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

17-
public static function get(string $unit): ?UnitMock
21+
public function has(string $unit): bool
1822
{
19-
if (!self::has($unit)) return null;
23+
return isset($this->mocks[$unit]);
24+
}
25+
26+
public function get(string $unit): ?UnitMock
27+
{
28+
if (!$this->has($unit)) return null;
2029

21-
return self::$mocks[$unit];
30+
return $this->mocks[$unit];
31+
}
32+
33+
public function register(string $unit, UnitMock $mock)
34+
{
35+
$this->mocks[$unit] = $mock;
2236
}
2337

24-
public static function register(string $unit, UnitMock $mock)
38+
public function count()
2539
{
26-
self::$mocks[$unit] = $mock;
40+
return count($this->mocks);
2741
}
2842
}

0 commit comments

Comments
 (0)