I'm doing unit tests on the different responses of the roads (usually the roads are protected with authentication). I managed to mock the user authentication. However, I can't mock the method of my models that calls to the database because I have database connection errors.
Do you know how mock his methods without calling him to the database ?
this is what I did.
- Controller
class XYZController extends Controller{
...
public function index(Request $request){
$user = Auth::user();
$person = $user->person()->first(); // how mock the method person - from the I have the database error.
$phone = $user->phone()->first();// how mock the method phone
$prefix = $phone->country()->first()->code; // how mock the method country
$email = $user->email;
$pays = Pays::where('xyz', false)->get(); // how mock the method person
...
return view('xyz',[
...
]);
}
...
}
- Test
class XYZTest extends TestCase{
public function testRouteMain(){
$user = factory(User::class)->make();
$person = factory(Person::class)->make();
$this->withoutMiddleware();
$this->be($user);
$mockUser = Mockery::mock(User::class);
$mockUser->shouldReceive('person')->andReturn(collect());
$mockUser->shouldReceive('first')->andReturn($person);
$this->app->instance(User::class, $mockUser);
$reponse = $this->get(route('xyz_route'));
$this->assertEquals(Response::HTTP_OK, $reponse->>getStatusCode(), 'The status code expected is '.Response::HTTP_OK);// I put the doubles ">>" on purpose , it's to avoid having the blockquote
}
}