1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelのユニットテストでサービスコンテナに入れるrequestを作る方法

Posted at

背景

Request::path()でその時のリクエストを元に処理をするような機能をテストをしようとした時に、FacadeのMockeryの機能を使って

Example.php
use Request;

...

    $request = Request::shouldReceive('path')->andReturn({欲しいパス});
    app()->instance('request', $request);

という感じでサービスコンテナに突っ込もうとしたら、以下のように怒られた。

BadMethodCallException: Method Mockery_1_Illuminate_Http_Request::setUserResolver() does not exist on this mock object

正直なところよく分からないが、どうやらサービスコンテナにrequestを突っ込むためにはsetUserResolver()というメソッドも定義してあげないといけないらしい。
そんなところまで定義しなきゃいけないとかmockを使うメリットが無くなるので普通にrequestインスタンスを作ってサービスコンテナに入れる方法にしたというもの。

結論

ExampleTest.php
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Illuminate\Http\Request;

...

    $symfonyRequest = SymfonyRequest::create($uri);
    $request = Request::createFromBase($symfonyRequest);
    app()->instance('request', $request);

解説

Laravel APIをみた限りでは、特にコンストラクタは無く、サーバー変数から作成する方法か、SymfonyRequestから作成する方法くらいしか見つからなかった。
サーバー変数をユニットテストでいじるのは違う気がしたので後者を選択。
SymfonyRequestコンストラクタでインスタンスを作れるので、これで作れば良い。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?