Pretty new to PHP, so forgive me if I missed something obvious.
I'm currently using Lumen (which is basically a basic Laravel, with only core dependencies) and Eloquent to manage persistent entities.
I want to write a Unit Test where I need to call a function which, at some point do an Eloquent query like this :
$errorMailRecipients = User::where('id_role', 1)
->where('some_value', 1)
->whereNotNull('email_addr');
My User.class, is a basic Eloquent entity :
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, Eloquence, Mappable;
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'modification_date';
/** Eloquent model configuration */
protected $connection = 'database_name';
protected $table = 'user';
protected $primaryKey = 'id';
// other stuff mapping, functions, etc ...
}
So, I created a test and trying, with Mockery, to mock this specific query :
class ImportTest extends TestCase
{
public function test_should_send_error_mail_when_receiving_empty_request()
{
// Given
$controller = new ImportController();
$mockedRecipients = // <- some Collection containing static data
$mock = Mockery::mock(User::class, function ($mock) use ($mockedRecipients) {
$mock->shouldReceive('where')->once()->andReturn($mockedRecipients);
});
$this->app->instance('App\Models\User', $mock);
// When
$controller->importDevices(new Request());
// Then
}
}
I tried many variants, and to decompose mocking into multiple lines :
$mock = Mockery::mock(User::class);
$this->app->instance('User', $mock);
$mock->shouldReceive('where')->once()->andReturn($mockedRecipients);
Also tried to remove the ->once(), and read the following guides :
- https://laravel.com/docs/5.8/mocking
- http://docs.mockery.io/en/latest/reference/alternative_should_receive_syntax.html
But so far, I kept having the following error when executing PHP Unit test :
Illuminate\Database\QueryException : SQLSTATE[HY000] [2002] Connection refused ...
Because, yeah, I don't have local database and it's still trying to hit it. Any thoughts ? Thank you