This is my feature test
class CreateImageTest extends TestCase
{
private static function headers(){
....
}
/**
* @test
*
*/
public function no_api_key_404()
{
......
}
/**
* @test
*
*/
public function not_logged_in_401()
{
......
}
/**
* @test
*
*/
public function empty_body_422()
{
....
}
}
I've always begun the test with middleware tests like what you see above (auth and API key middleware). I'm going to use the same test procedure for endpoints with similar middleware (there are a lot of them). How can I do that without being redundant? I was thinking to make a trait for the recurring testing pattern but I have no idea how to do that.
CodePudding user response:
I think you should be able to achieve what you want by introducing an AbstractTestCase file. This file could contain all of your repeating middleware tests and be extended by the Test classes that need it.
Your abstract class could look something like this:
<?php
abstract class AbstractMiddlewareTestCase extends TestCase
{
protected array $headers = [];
public function no_api_key_404()
{
$this->get('your_api_url', $this->headers)
->seeStatusCode(404);
}
// Add any other shared tests here
}
And then you could extend from your regular test file like so:
<?php
class CreateImageTest extends AbstractMiddlewareTestCase
{
use ApiKeyTrait;
public function create_image() {
$this->get('your_api_url', $this->headers)
->seeStatusCode(200);
}
}
Additionally, you could leverage Traits to cater to multiple types of Middleware. I.e. if your create image endpoint is api key authorised you could have an ApiKeyTrait that could look something like this:
<?php
trait ApiKeyTrait
{
public function setUp(): void
{
parent::setUp();
$this->headers = [
'X-API-KEY' => 'yourKey',
];
}
}