toothful
toothful

Reputation: 892

How to test my simple method in laravel

I have a method in laravel 5.3 project like below:

/**
* returns each section of current url in an array
*
* @return array
*/
public function getUrlPath()
{
    return explode("/", $this->request->path());
}

How can I create a unit test method to test this method? I guess I need to mock a http get request and request instance. But, I do not know how to do that.

Upvotes: 0

Views: 124

Answers (1)

melanholly
melanholly

Reputation: 772

You should make your method self-contained like so

use Request;
/**
* returns each section of current url in an array
*
* @return array
*/
public function getUrlPath(Request $request)
{
    return explode("/", $request->path());
}

You can add the Request as a parameter to the containing class like that:

use Request; //it is a facade https://laravel.com/docs/5.3/facades 
class MyRequestHandler
{
    protected $request;
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function getUrlPath()
    {
        return explode("/", $this->request->path());
    }
}

Than test is like that:

public function testGetUrlPath(){
    $expected = ['url','to','path'];
    $request = Request::create(implode('/', $expected)); // https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L313
    $class = new MyRequestHandler($request);

    // Getting results of function so we can test that it has some properties which were supposed to have been set.
    $result = $class->getUrlPath();
    $this->assertEquals($expected, $result);
}

Upvotes: 1

Related Questions