我在laravel 5.3项目中有一个方法,如下所示:
/**
* returns each section of current url in an array
*
* @return array
*/
public function getUrlPath()
{
return explode("/", $this->request->path());
}
如何创建单元测试方法来测试此方法?我想我需要模拟一个http get请求和请求实例。但是,我不知道该怎么做。
答案 0 :(得分:1)
你应该让你的方法自包含
use Request;
/**
* returns each section of current url in an array
*
* @return array
*/
public function getUrlPath(Request $request)
{
return explode("/", $request->path());
}
您可以将Request
作为参数添加到包含的类中,如下所示:
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());
}
}
比测试就是这样:
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);
}