草庐IT

php - 在 Laravel 中测试 Controller 的正确方法是什么?

coder 2024-04-20 原文

我正在重写现有的 Laravel 4 应用程序以确保进行充分的测试。长话短说,我已经使用 TDD 方法重写了我的 AccountController 类,但我有点头疼。

考虑以下呈现包含用户列表的页面的方法:

public function getIndex()
{
    // build the view
    //
    return \View::make('account.list-users')
        ->with('users', \Sentry::getUserProvider()->findAll());
}

我正在使用 Smarty 呈现我的 View 并使用 Sentry 进行身份验证。

现在,我想写一些这样的测试:

public function test_getIndex()
{
    // arrange
    //

    // set up some mocks here...


    // act
    //
    $response = $this->client->request("GET", "/list-users");


    // assert
    //

    // test for <table class="table">
    $this->assertFalse($response->filter("table.table")==null, "table not found");

    // test for some <a> tags for the "update" buttons
    $element = $response->filter("td a")->first()->extract(array("href", "class", "_text"));
    $this->assertTrue(strstr($element[0][0],"/my-update-url")!="");
    $this->assertTrue(strstr($element[0][1],"btn btn-xs btn-success")!="");
    $this->assertTrue(strstr($element[0][2],"Active")!="");

    // test for some other markup...

}

我一直在关注 Jeffrey Way 的书 Laravel Testing Decoded 并编写了类似上面的测试,它们运行良好。

令人头疼的是“在这里设置一些模拟...”部分。具体来说,我需要设置的模拟数量是荒谬的。这是因为,作为一个更大的 Web 应用程序的一部分,我正在使用一个 View composer,它将数据添加到 View 模型:当前用户模型、菜单结构、警报消息、新闻消息、应用程序版本号等。我我已经通过使用“基本”模板进行测试来减少其中的大部分内容,但它仍然有很多东西 - 以至于我要编写数百行代码来测试这个简单的单行方法。

有更好的方法吗?

在我看来,有两种方法可以做到这一点:

一个。我一直在做的方式

B.模拟 \View::make 调用,以便绕过我所有的模板渲染 - 就像这样

public function test_getIndex()
{
    // arrange
    //
    $userList = "this is a list of users";

    $userProvider = Mockery::mock("\Cartalyst\Sentry\Users\Eloquent\Provider");

    \Sentry::shouldReceive("getUserProvider")
        ->once()
        ->andReturn($userProvider);

    $userProvider->shouldReceive("findAll")
        ->once()
        ->andReturn($userList);

    $view = Mockery::mock("\Illuminate\View\View");

    \View::shouldReceive("make")
        ->with("account.list-users")
        ->once()
        ->andReturn($view);

    $view->shouldReceive("with")
        ->with("users", $userList)
        ->once()
        ->andReturn($view);

    $view->shouldReceive("render")
        ->once()
        ->andReturn("results");

    // act
    //
    $response = $this->call("GET", "/list-users");

    // assert
    //
    $this->assertResponseOk();
}

如果我采用这种方法,测试会简单得多,我只测试 Controller 方法中的代码,但我并没有真正测试调用该路由所涉及的所有内容(这可能是一件好事或者可能不会 - 我不确定)并且我担心我无法获得足够的保险。

那么,执行此操作的最佳方法是什么:(A)、(B) 或其他方法?

编辑

我对我的 Controller 方法的测试有相当多的困惑,@TheShiftExchange 在下面的回答和评论中变得更加清晰。我将尝试在这里解决这个问题,作为编辑,因为它给我更多的空间来讨论这个问题。

考虑下面答案中给出的第二个示例:

public function testMethod()
{
    $this->call('GET', '/list-users');

    $this->assertViewHas('users', \Sentry::getUserProvider()->findAll());
}

如果我运行这个测试,它会工作,但它会访问数据库,我试图通过模拟一些东西来避免这种情况。

所以,我可以稍微扩展一下这个测试:

public function testMethod()
{
    \Sentry::shouldReceive("getUserProvider")
        ->once()
        ->andReturn($userProvider);
    // plus a mock of the UserProvider class,...


    $this->call('GET', '/list-users');

    $this->assertViewHas('users', \Sentry::getUserProvider()->findAll());
}

此测试将 起作用,因为除了 Controller 方法所需的模拟之外,我还需要对我的 View 编辑器中的代码进行模拟。此代码包括 $currentUser =\Sentry::getUser()(用户名显示在我的应用程序页面的右上角)。

所以代码实际上变成了:

public function testMethod()
{
    \Sentry::shouldReceive("getUserProvider")
        ->once()
        ->andReturn($userProvider);
    // plus a mock of the UserProvider class,...

    // plus a mock of ThisClass

    // and a mock of ThatClass

    // and a mock of SomeOtherClass

    // etc.

    // etc.

    $this->call('GET', '/list-users');

    $this->assertViewHas('users', \Sentry::getUserProvider()->findAll());
}

它很快就会失控。

这表明我做错了什么,但我不确定是什么。我怀疑问题源于我不确定我在这里测试的到底是什么。

所以,毕竟,问题变成了:

当我测试 Controller 的方法时,我到底想测试什么?

  1. Controller 方法中的代码?或者,

  2. 从请求到响应的全过程?

我要测试的是第一项——只是 Controller 方法中的代码。我的问题中的示例非常简单,但我确实有一些 Controller 方法可以根据用户输入执行表单验证或重定向等操作 - 我想测试该代码。

也许,我不需要通过 $this->call() 来测试代码,而是直接调用 Controller 方法?

最佳答案

作为 Laravel 框架的一部分,it includes some testing helpers .在这些助手中包括 View 测试助手:

断言 View 有一些数据

public function testMethod()
{
    $this->call('GET', '/');

    $this->assertViewHas('name');
    $this->assertViewHas('age', $value);
}

所以你可以这样做:

public function testMethod()
{
    \Sentry::shouldReceive("getUserProvider")
    ->once()
    ->andReturn('foo');

    $this->call('GET', '/');

    $this->assertViewHas('users', 'foo');
}

关于php - 在 Laravel 中测试 Controller 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23959302/

有关php - 在 Laravel 中测试 Controller 的正确方法是什么?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  6. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  7. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  8. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  9. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  10. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

随机推荐