Skip to content

Instantly share code, notes, and snippets.

@inxilpro
Last active February 10, 2022 18:15
Show Gist options
  • Save inxilpro/fe7428da7e0527f11c2928a18143ac51 to your computer and use it in GitHub Desktop.
Save inxilpro/fe7428da7e0527f11c2928a18143ac51 to your computer and use it in GitHub Desktop.
<?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