[英]Laravel testing requests
I'm working on a large Laravel app, currently on v8.45.1 which has never had tests, so I'm working to get it to a point where we can start writing unit & feature tests.我正在开发一个大型 Laravel 应用程序,目前在 v8.45.1 上从未进行过测试,所以我正在努力让它达到我们可以开始编写单元和功能测试的程度。
I'm hitting an issue where the two request classes ( App\\Core\\Request
and App\\Core\\FormRequest
) both use a trait RequestTrait
which holds a set of utility methods.我遇到了一个问题,其中两个请求类(
App\\Core\\Request
和App\\Core\\FormRequest
)都使用一个特征RequestTrait
,它包含一组实用程序方法。
This obviously works fine in local/staging/production, but when I run the test suite it complains that none of the methods provided by the trait exist:这显然在本地/暂存/生产中运行良好,但是当我运行测试套件时,它抱怨该特性提供的任何方法都不存在:
Method Illuminate\Http\Request::isFromTrustedSource does not exist.
They are being called in various places as Request::isFromTrustedSource()
or request()->isFromTrustedSource()
.它们在不同地方被称为
Request::isFromTrustedSource()
或request()->isFromTrustedSource()
。
I can imagine that when running the app in the test environment, there may be differences to the request.我可以想象,在测试环境中运行应用程序时,请求可能会有所不同。 Is it using a different class, or does the trait not apply for some reason?
它是使用不同的类,还是由于某种原因该特性不适用?
I think, I found your problem - App\\Core\\Request extends Illuminate\\Http\\Request and in index.php you use App\\Core\\Request我想,我发现了你的问题 - App\\Core\\Request extends Illuminate\\Http\\Request 并且在 index.php 你使用 App\\Core\\Request
The problem is in Illuminate\\Foundation\\Testing\\Concerns\\MakesHttpRequests::call()问题出在 Illuminate\\Foundation\\Testing\\Concerns\\MakesHttpRequests::call()
When you use $this->get(...) in test suite - this method bootstrap app with standard request - not with your App\\Core\\Request当您在测试套件中使用 $this->get(...) 时 - 此方法使用标准请求引导应用程序 - 而不是您的 App\\Core\\Request
You can override this method in base tests/TestCase.php and pass your own request.您可以在基本测试/TestCase.php 中覆盖此方法并传递您自己的请求。
Unfortunately, it has no contract, than you cannot work with this through $this->app->bind()不幸的是,它没有合同,因为您无法通过 $this->app->bind() 使用它
Something like this:像这样的东西:
class TestCase extends BaseTestCase
{
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
//other code
$response = $kernel->handle(
$request = \App\Core\Request::createFromBase($symfonyRequest)
);
//other code
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.