0

I need to test a function in UserController :

public function CreateUser(Request $request): Response
{    
    $user = User::firstOrCreate(['device_id' => $request->device_id]);
    return Response(['status'=> 'user created successfully'],200);
} 

and I create a test function same as following:

public function testCreateUser()
{
    $mockUser = Mockery::mock(new App\User());
    $this->app->instance(App\User::class, $mockUser);
    $this->post(route('user_create'), ['device_id' => 'REC00ER']);
    ...
}

but this function create a real row in database. how to i can mock database for this request ?

Sin Sin
  • 3
  • 2

1 Answers1

0

If you don't want to create a new row in DB you can use DatabaseTransactions.

Just add it to your test:

use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use DatabaseTransactions;
...

More you can read here inside transactions.

Also, one helpful answer.

Good luck!

mare96
  • 3,749
  • 1
  • 16
  • 28
  • thanks its work for me, so can i delete `$mockUser = Mockery::mock(new App\User());` ? – Sin Sin Mar 29 '20 at 17:40
  • @SinSin If you need you can use `$mockUser = User::create()` to create new user, and it will exist for testing purposes and the database will not be updated. If the answer is helpful please upvote it and mark. Thanks! :) – mare96 Mar 29 '20 at 17:42
  • Is this method safe because I have important data in my database? – Sin Sin Mar 29 '20 at 17:45
  • 1
    Thank you very much for your help – Sin Sin Mar 29 '20 at 17:51