如何在laravel中测试我的简单方法
我在laravel 5.3项目中有如下方法:如何在laravel中测试我的简单方法,laravel,automated-tests,laravel-5.3,Laravel,Automated Tests,Laravel 5.3,我在laravel 5.3项目中有如下方法: /** * returns each section of current url in an array * * @return array */ public function getUrlPath() { return explode("/", $this->request->path()); } 如何创建单元测试方法来测试此方法?我想我需要模拟http get请求和请求实例。但是,我不知道怎么做 你应该让你的方法像这样独
/**
* returns each section of current url in an array
*
* @return array
*/
public function getUrlPath()
{
return explode("/", $this->request->path());
}
如何创建单元测试方法来测试此方法?我想我需要模拟http get请求和请求实例。但是,我不知道怎么做 你应该让你的方法像这样独立
use Request;
/**
* returns each section of current url in an array
*
* @return array
*/
public function getUrlPath(Request $request)
{
return explode("/", $request->path());
}
您可以将请求
作为参数添加到包含的类中,如下所示:
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);
}
而测试是这样的:
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);
}
如果您认为helper方法是自包含的,并将依赖项作为参数提供,可能会更好。这将使它易于测试<代码>公共函数getUrlPathElements($path)将允许您直接对其进行单元测试,而无需使用Laravel路由机制。您指的是类似于此问题的方法吗?