unittest laravel caching issue

use*_*863 5 phpunit caching laravel-4

I am using laravel 4 and created a class under its own namespace. Within this class there's a method that retrieves data and caches it. I also wrote a very small unit test to check if caching works. For some reason, caching does not work when unit testing, but does work when accessing through browser. I even modified app/config/testing/cache.php driver to use apc instead of array and it still doesn't work.

Here's the code:

<?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");
    }

}
Run Code Online (Sandbox Code Playgroud)

The routes.php file (works through browser, result: 'YES testing'):

Route::get('test-caching', 'site\UserController@register');
Run Code Online (Sandbox Code Playgroud)

The test (does not work with phpunit, result: '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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Did anyone else experience this problem? Any solutions?

Lun*_*fel 2

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

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

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;
     }
}
Run Code Online (Sandbox Code Playgroud)

在你的测试中应该看起来像这样

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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