2
Hello, all right with you?
I created the following class for my own mini-framework (developed for study purposes).
<?php
declare(strict_types=1);
namespace Atlas\Core;
final class Request
{
private $uri;
public function __construct()
{
$this->uri = $_SERVER['REQUEST_URI'];
}
public function path(): string
{
return $this->uri;
}
}
How can I test the method path
of that class with Phpunit? I tried something like this
<?php
declare(strict_types=1);
namespace Atlas\Tests\Core;
use PHPUnit\Framework\TestCase;
use Atlas\Core\Request;
final class RequestTest extends TestCase
{
private $request;
public function assertPreConditions(): void
{
$this->request = new Request();
}
public function testCheckIfPathMethodReturnString(): void
{
$this->assertIsString($this->request->path());
}
}
But it didn’t work. This class Request
works perfectly when accessed by the browser. However, when I try to test it with Phpunit, this method returns null
. Apparently $_SERVER values change since what Phpunit does is not a conventional web request.
Ideas?
Thank you very much.
Ideas? Yes. Remove your class dependency with global variables and you’ll be able to test more easily. Why not receive the URL as a parameter in the constructor? So, during the tests, you can set exactly the URL to be tested. In the production application it will be enough for you to pass the value of
$_SERVER['REQUEST_URI']
as a parameter to function as expected.– Woss
@Woss Cara, doesn’t that make sense? I’ll wait to see if you have more equally useful answers to add something to the question. In the meantime, why don’t you post an answer with what you told me? Then, it’s likely I’ll dial!
– Clayderson Ferreira