Laravel 5 - Using Mockery to mock Eloquent model

岁酱吖の 提交于 2019-12-06 09:36:01

Okay, after finding multiple posts by Jeffrey Way (the guy behind Laracasts) recommending people to stop mocking Eloquent objects and instead use in memory databases I've tried that approach. I thought this would perhaps be very usable for other users having the same problems in the future, so I'll explain below.

Right now I've edited the my 'config/database.php' file to support in-memory database option using sqlite:

'sqlite' => [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ],

Next on top of the file you'll see the following configuration:

'default' => env('DB_CONNECTION', 'mysql'),

This can stay the same, it means that Laravel will check your .env variables to find a 'DB_CONNECTION' or else use mysql as default. This is probably what you'd like to do when running your application as usual. However with testing you would like to override this configuration and set the database config to 'sqlite' temporarily. This can be done by adding the 'DB_CONNECTION' variable to your .env file:

DB_CONNECTION=mysql 

Finally in your phpunit.xml, the configuration file used by Laravel to instantiatie the unit tests, you have to tell that when testing this variable should be set to 'sqlite':

<env name="DB_CONNECTION" value="sqlite"/> 

Now you are done and Laravel will start up an invisible in-memory database everytime you are about to go testing. Don't forget to add the following line to tests that need the database.

use \Illuminate\Foundation\Testing\DatabaseMigrations;

It will tell Laravel run your database migrations before starting the tests, so you can use the tables like you normally would.

This way it works perfectly for me! Hope you guys can use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!