exSnake's avatar

Could a unit test use databases?

Could a unit test use databases?

I mean, i want to make a test that assert if a give role has been assigned

/** @test */
    public function a_admin_is_an_admin()
    {
        $user = factory(\App\User::class)->create();
        $role = factory(\App\Role::class)->create(['name' => 'Admin', 'label' => 'Amministratore']);
        $user->assignRole($role);

        $this->assertEquals(true, $user->isAdmin());
    }

Is this an unit or a feature test?

If it is a Unit test, should it use database?

If not how i can rewrite this?

0 likes
4 replies
Tray2's avatar
Tray2
Best Answer
Level 74

I would say it's a unit test since it test the $user->assignRole() method.

Yes a unit test can talk to the database if it needs to.

1 like
tykus's avatar

It is more an Integration than a Unit test IMO. But different people will argue nomenclature... For testing purists, a Unit test should be concerned with a single unit of code, which your example is not.

Personally I don't care what it is called, or if it touches the database once it gives me confidence about my application(s) working as expected.

1 like
Tray2's avatar

I agree with @tykus on this

Personally I don't care what it is called, or if it touches the database once it gives me confidence about my application(s) working as expected.

exSnake's avatar

Thank you guys, i'd like to select both as best answer but can't.

Please or to participate in this conversation.