Skip to content

Commit b2fb337

Browse files
Improve Testing (#5885)
* Improve Test * feat: Add container to InteractsWithContainer trait This commit adds a property `container` of type `ContainerInterface` to the `InteractsWithContainer` trait. It also removes a redundant annotation and an unnecessary `PHPStan` ignore statement. The `instance()` method now sets instances using the container object. Co-authored-by: 李铭昕 <[email protected]>
1 parent 8ddecf6 commit b2fb337

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

src/Concerns/InteractsWithContainer.php

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020

2121
trait InteractsWithContainer
2222
{
23+
/**
24+
* @var null|ContainerInterface|\Hyperf\Di\Container
25+
*/
2326
protected ?ContainerInterface $container = null;
2427

2528
/**
@@ -82,14 +85,29 @@ protected function spy($abstract, Closure $mock = null)
8285
return $this->instance($abstract, Mockery::spy(...array_filter(func_get_args())));
8386
}
8487

85-
protected function refreshContainer(): void
88+
protected function createContainer(): ContainerInterface
8689
{
87-
$this->container = ApplicationContext::setContainer($this->createContainer());
88-
$this->container->get(\Hyperf\Contract\ApplicationInterface::class);
90+
return new Container((new DefinitionSourceFactory())());
8991
}
9092

91-
protected function createContainer(): ContainerInterface
93+
protected function getContainer(): ContainerInterface
9294
{
93-
return new Container((new DefinitionSourceFactory())());
95+
return $this->container;
96+
}
97+
98+
protected function flushContainer(): void
99+
{
100+
$this->container = null;
101+
}
102+
103+
protected function setContainer(ContainerInterface $container): void
104+
{
105+
$this->container = $container;
106+
}
107+
108+
protected function refreshContainer(): void
109+
{
110+
$this->container = ApplicationContext::setContainer($this->createContainer());
111+
$this->container->get(\Hyperf\Contract\ApplicationInterface::class);
94112
}
95113
}

src/TestCase.php

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,12 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase
2626

2727
protected function setUp(): void
2828
{
29-
/* @phpstan-ignore-next-line */
30-
if (! $this->container) {
31-
$this->refreshContainer();
32-
}
29+
$this->refreshContainer();
3330
}
3431

3532
protected function tearDown(): void
3633
{
37-
$this->container = null;
34+
$this->flushContainer();
3835

3936
try {
4037
m::close();

0 commit comments

Comments
 (0)