Last active
February 10, 2022 18:15
-
-
Save inxilpro/fe7428da7e0527f11c2928a18143ac51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Support; | |
use Closure; | |
use Illuminate\Support\Facades\App; | |
use Illuminate\Support\Str; | |
use Illuminate\Testing\Assert; | |
trait ShouldBeMocked | |
{ | |
protected bool $allow_when_testing = false; | |
public function allowWhenTesting(): self | |
{ | |
$this->allow_when_testing = true; | |
return $this; | |
} | |
public function shouldBeMocked(): self | |
{ | |
$this->allow_when_testing = false; | |
return $this; | |
} | |
public function withoutMocking(Closure $callback) | |
{ | |
try { | |
$this->allowWhenTesting(); | |
return $callback() ?? $this; | |
} finally { | |
$this->shouldBeMocked(); | |
} | |
} | |
protected function guardAgainstRunningInTests(): void | |
{ | |
if ($this->allow_when_testing || ! App::runningUnitTests()) { | |
return; | |
} | |
$name = get_class($this); | |
$frame = collect(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)) | |
->first(function($backtrace) { | |
return Str::startsWith($backtrace['function'], 'test') | |
|| Str::endsWith($backtrace['class'], 'Test'); | |
}); | |
Assert::fail("Expected {$name} to be mocked in {$frame['class']}::{$frame['function']}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment