【问题标题】:unittest laravel caching issueunittest laravel 缓存问题
【发布时间】:2014-10-07 09:54:20
【问题描述】:

我正在使用 laravel 4 并在其自己的命名空间下创建了一个类。在这个类中有一个检索数据并缓存它的方法。我还编写了一个非常小的单元测试来检查缓存是否有效。出于某种原因,缓存在单元测试时不起作用,但在通过浏览器访问时起作用。我什至修改了app/config/testing/cache.php 驱动程序以使用 apc 而不是数组,它仍然不起作用。

代码如下:

<?php namespace site;
use Cache;

class UserController {
    public function testCaching( )
    {
        Cache::put('test', 'testing', 1);
        if (Cache::has('test')) die("YES: " . Cache::get('test')); die("NO");
    }

}

routes.php 文件(通过浏览器运行,结果:'YES testing'):

Route::get('test-caching', 'site\UserController@register');

测试(不适用于 phpunit,结果:'NO'):

<?php namespace site;
use Illuminate\Foundation\Testing\TestCase;
class SiteTest extends TestCase {
    /** @test */
    public function it_caches_vendor_token()
    {   
        $user = new UserController();
        $user->testCaching();
    }
}

还有其他人遇到过这个问题吗?有什么解决办法吗?

【问题讨论】:

  • 同样的问题,现在正在尝试解决

标签: caching laravel-4 phpunit


【解决方案1】:

在单元测试中,我会得到 Cache not found in ...

问题是我没有正确引导我的测试环境。由于我的应用程序没有正确引导,它不会注册别名(Cache、Eloquent、Log 等)。要正确引导,您需要扩展提供的 TestCase,如下所示

use Illuminate\Foundation\Testing\TestCase as BaseCase;

class TestCase extends BaseCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
     protected $baseUrl = 'http://localhost.dev';

     /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
     public function createApplication()
     {
         $app = include __DIR__.'/../bootstrap/app.php';

         $app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();

         return $app;
     }
}

在你的测试中应该是这样的

class MyBrandNewTest extends TestCase 
{
    // You can omit to override this method if you
    // do not have custom setup logic for your test case
    public function setUp()
    {
        parent::setUp();

        // Do custom setup logic here
    }
}

parent::setUp() 将调用 BaseTest 中的 setUp 方法,该方法将引导测试环境。

【讨论】:

  • 你为什么要通过调用父方法来覆盖父 setUp
  • 我这样做是因为我经常在我的测试用例中使用setUp来生成数据。但是在这里,因为它是空的,所以没有意义。我将进行编辑以使其更清楚。因此,如果您不需要在 setUp 处做任何事情,则根本不要放置该方法。但是如果你这样做了,你应该重写方法,调用父方法,然后做你自己的自定义逻辑。
  • 好的,请做。我已经看到很多人不必要地覆盖它(也许他们只是留下自动生成的代码)并且它变得有点让人讨厌。
猜你喜欢
  • 2020-11-04
  • 2021-11-18
  • 2018-11-13
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
  • 2013-06-10
  • 2017-11-04
相关资源
最近更新 更多