【问题标题】:How to mock properly Illuminate\Http\Request class from Laravel如何从 Laravel 正确模拟 Illuminate\Http\Request 类
【发布时间】:2018-05-26 09:50:45
【问题描述】:

我正在尝试从包含使用 Laravel 的 request() 助手的方法的类中测试方法。方法是这样的:

类别类

public function getCanonicalUrl()
{
    return preg_match('/\/sale\/./', request()->getRequestUri())
         ? ''
         : url($this->getUrlKey());
}

测试应该使这个助手在执行 getRequestUri() 时正确捕获 URI,但它实际上返回一个空字符串。这是我为测试进行的一千次尝试之一。

测试

public function testCanonical()
{
    // ...

    $requestMock = Mockery::mock(Request::class)
      ->shouldReceive('getRequestUri')
      ->andReturn('/sale/random-string');

    $this->app->instance(Request::class, $requestMock);

    // ...
}

关于如何实现这一点的任何想法? 提前致谢。

【问题讨论】:

    标签: php laravel unit-testing mocking mockery


    【解决方案1】:

    你不应该嘲笑 Request 门面。相反,在运行测试时将所需的输入传递给 HTTP 帮助方法,例如 get 和 post。

    https://laravel.com/docs/5.5/mocking#mocking-facades

    【讨论】:

    • 所以$this->get($path) 是解决此问题的正确且简单的方法。谢谢
    【解决方案2】:

    根据https://stackoverflow.com/a/61903688/135114, 如果

    1. 您的被测函数采用$request 参数,并且
    2. 您不需要对请求做一些时髦的事情 - 真正的路由路径对您来说已经足够好了

    ...那么您不需要“模拟”请求(例如,嘲弄),
    你可以创建一个Request并传递它,例如

    public function test_myFunc_condition_expectedResult() {
        ...
        $mockRequest = Request::create('/path/that/I_want', 'GET'); 
        $this->assertTrue($myClass->myFuncThat($mockRequest));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-26
      • 2015-08-03
      • 2017-06-28
      • 2021-03-06
      • 2015-04-09
      相关资源
      最近更新 更多