From e1cae7e616de7354f744d77c7eff69657c27d462 Mon Sep 17 00:00:00 2001 From: Khalil Laleh Date: Mon, 22 Nov 2021 18:33:52 +0330 Subject: [PATCH] [8.x] Forget and clear a mocked/spied instance of an object in the container (#39713) * Forget and clear a mocked/pied instance of an object in the container * Style Fix * Test for forgetMock * Update InteractsWithContainer.php Co-authored-by: Taylor Otwell --- .../Concerns/InteractsWithContainer.php | 13 ++++++++++++ .../Concerns/InteractsWithContainerTest.php | 21 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php index c84852e0040c..6949f6f8c5da 100644 --- a/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php +++ b/src/Illuminate/Foundation/Testing/Concerns/InteractsWithContainer.php @@ -77,6 +77,19 @@ protected function spy($abstract, Closure $mock = null) return $this->instance($abstract, Mockery::spy(...array_filter(func_get_args()))); } + /** + * Instruct the container to forget a previously mocked / spied instance of an object. + * + * @param string $abstract + * @return $this + */ + protected function forgetMock($abstract) + { + $this->app->forgetInstance($abstract); + + return $this; + } + /** * Register an empty handler for Laravel Mix in the container. * diff --git a/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php b/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php index 4bf62fcfb738..dddc721de22e 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php @@ -27,4 +27,25 @@ public function testWithMixRestoresOriginalHandlerAndReturnsInstance() $this->assertSame($handler, resolve(Mix::class)); $this->assertSame($this, $instance); } + + public function testForgetMock() + { + $this->mock(IntanceStub::class) + ->shouldReceive('execute') + ->once() + ->andReturn('bar'); + + $this->assertSame('bar', $this->app->make(IntanceStub::class)->execute()); + + $this->forgetMock(IntanceStub::class); + $this->assertSame('foo', $this->app->make(IntanceStub::class)->execute()); + } +} + +class IntanceStub +{ + public function execute() + { + return 'foo'; + } }