gpt4 book ai didi

unit-testing - Laravel 测试 - 创建路由的问题

转载 作者:行者123 更新时间:2023-11-28 20:42:42 25 4
gpt4 key购买 nike

我对测试包时的路由有疑问。函数 setRoutes 在测试文件中创建新路由,如下所示:

class PackageTests extends \Orchestra\Testbench\TestCase {
protected function setRoutes()
{
Route::group([
'prefix' => Package::functionToCall1(),
'before' => 'filter'
], function() {

Route::get('/', function () {
return "hello";
});

});
Route::enableFilters();
}
protected function getEnvironmentSetUp($app)
{
$this->app = $app;
$this->setRoutes();
Config::set('app.url', "http://localhost/" );
}
public function testFunction1()
{
$crawler = $this->call(
'GET',
'http://localhost/'
);
// doing this call, the function on the prefix is called
$this->assertResponseOk();
}
}

在前缀中调用的函数内,functionToCall1() url 未成功获取。执行 phpunit 时,调用 URL::current() 返回“/”,调用 Request::fullUrl() 返回“http://:”,但是当在浏览器中执行 url 时,它们会返回完整的 url。这是包的代码:

class Package
{
function functionToCall1()
{
var_dump(URL::current() ); // returns "/"
var_dump(Request::fullUrl()); // returns "http://:"
// I want them to return 'http://localhost'
}
}

我尝试设置 url Config::set('app.url', "http://localhost/"); 但没用。

综上所述,有没有办法调用前缀中的函数并获取测试url?

谢谢,非常感谢您的回答:)

最佳答案

我也遇到过类似的问题。
我的解决方案是在这里找到的: Mocking Laravel's Request::segment method

显然,测试 Request facade 存在操作顺序问题。
我试图在构建请求之前使用 Request::segments() ,所以从来没有任何段可以返回。
我想这和 Request::fullUrl() 有同样的问题。

这是我的解决方案:

class MyTestClass extends TestCase
{
public function setUp()
{
// No call to parent::setUp()

$this->app = $this->createApplication();
$this->app->request->server->set('REQUEST_URI', '/some/uri');
$this->client = $this->createClient();
$this->app->boot();
}

public function testWhatever()
{
$this->call('GET', '/some/uri');
}
}

这使我能够正确地获取请求数据,即使它看起来很糟糕。

关于unit-testing - Laravel 测试 - 创建路由的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26385938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com