【问题标题】:How to test my simple method in laravel如何在 laravel 中测试我的简单方法
【发布时间】:2017-06-23 07:45:35
【问题描述】:

我在 laravel 5.3 项目中有一个方法,如下所示:

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

如何创建单元测试方法来测试此方法?我想我需要模拟一个 http 获取请求和请求实例。但是,我不知道该怎么做。

【问题讨论】:

  • 如果您认为辅助方法是自包含的,并且将依赖项作为参数提供,那可能会更好。它将使其易于测试。 public function getUrlPathElements($path) 将允许您直接对其进行单元测试,而无需使用 Laravel 路由机制。
  • 你是说这个问题中的方法吗? stackoverflow.com/questions/29781103/…

标签: laravel automated-tests laravel-5.3


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    相关资源
    最近更新 更多