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

标签 unit-testing testing laravel laravel-routing

我对测试包时的路由有疑问。函数 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/

相关文章:

testing - 如何在不要求参数函数可变的情况下测试元函数?

php - 使用 Laravel 重定向到没有获取参数的路由

typescript - 在 JestJS 中测试私有(private)方法

python - 如何跨 pytest 装置同步参数化?

iphone - Xcode 中逻辑测试和应用程序测试的区别?

Python - 测试一个抽象基类

php - 如何让我在 Heroku 上的 Laravel 项目使用 Heroku Postgres?

php - 具有任意数量 URL 段的 Laravel 4 路由

java - Android/Java 单元测试 - 如何在 java.lang.reflect.Method 中使用参数?

javascript - Jasmine .js : How to spyOn a dropdown list