Created
August 15, 2019 13:52
-
-
Save Braunson/4699accbb826f2e59a4e5ff53d4c27ad to your computer and use it in GitHub Desktop.
app/Http/Middleware/CollectCodeCoverage.php + tests/Feature/xCoverage.php Test code coverage middleware for Laravel 5.8+
This file contains hidden or 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\Http\Middleware; | |
use Closure; | |
class CollectCodeCoverage { | |
/** | |
* Used for code coverage when running unit tests | |
* @var array | |
* | |
* Register this in your Kernel file in the `$middleware` group! | |
*/ | |
static $routesTested = []; | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$response = $next($request); | |
if (app()->runningUnitTests()) { | |
// Record code coverage | |
static::$routesTested[] = [ | |
'url' => $request->getRequestUri(), | |
'name' => optional(\Route::getCurrentRoute())->getName() ?? 'unknown', | |
'method' => $request->getMethod(), | |
]; | |
} | |
return $response; | |
} | |
} |
This file contains hidden or 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 Tests\Unit; | |
use Tests\TestCase; | |
use App\Http\Middleware\CollectCodeCoverage; | |
/** | |
* | |
* This test class needs to run LAST! PhpUnit will run them in alphabetical order; | |
* this is the simplest way to do that | |
* | |
* Class xCoverageTest | |
* @package Tests\Unit | |
*/ | |
class xCoverageTest extends TestCase | |
{ | |
public function testCheckAllRoutesTested() | |
{ | |
$missingRoutes = []; | |
$routes = \Illuminate\Support\Facades\Route::getRoutes(); | |
$routesTested = CollectCodeCoverage::$routesTested; | |
$list = collect($routesTested)->groupBy("name"); | |
foreach ($routes as $route) { | |
$routeName = $route->getName(); | |
$hits = $list->get($routeName); | |
foreach ($route->methods() as $method) { | |
if ($method === 'HEAD') { | |
continue; | |
} elseif ($hits === null || $hits->where("method", '=', $method)->count() === 0) { | |
$missingRoutes[] = $routeName . ' ' . $method; | |
} | |
} | |
} | |
asort($missingRoutes); | |
$this->assertSame(0, count($missingRoutes), "Missing feature tests for Routes:\n" . implode("\n", $missingRoutes)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment