Aaron
Aaron

Reputation: 4480

Laravel unit testing calling a method that calls that database

I have been trying to set up a unit test that calls a method where the database is called. I have looked up mocking and faker and am confused about what to do.

In my test I call

Logic::lookForClassificationException($exception_array, $content);

In my method there is a call to my ClassificationException model

$exceptions = ClassificationException::select('exception')->get(); 

I am confused about how to set up a mock for this. ClassificationException is a table that has an id, exception, previous_word, and after_word.

How do I mock or fake the setup?

Upvotes: 0

Views: 308

Answers (1)

Paras
Paras

Reputation: 9465

One way to do tests using DB is to setup an in memory sqlite database for tests like so:

use Illuminate\Database\Capsule\Manager as DB;

protected function setUpDatabase()
{
    $database = new DB;

    $database->addConnection(['driver' => 'sqlite', 'database' => ':memory:']);
    $database->bootEloquent();
    $database->setAsGlobal();
}

Then, call this function in your setUp method of the test class.

This is just one of many possible ways and may not suit your needs. Another way would be to setup a separate database for tests and use a separate .env for tests

In my experience, tests break down when you try to mock Eloquent models

Upvotes: 1

Related Questions