odan / slim4-skeleton

A Slim 4 Skeleton
https://odan.github.io/slim4-skeleton/
MIT License
446 stars 80 forks source link

Unit Testing with Fixtures #22

Closed KipchirchirIan closed 4 years ago

KipchirchirIan commented 4 years ago

Thank you for this amazing project once again. I am trying to figure out how to use fixtures(UserFixture class & UserCreatorRepositoryTest class) with unit testing and I am completely lost. I have tried using debug when testing and I am still unable to tell whether the fixtures are being used or not. I can't also tell where DatabaseTestTrait comes into play and how it's being used or when it is executed. If it is possible, I'd like to request that you please post a quick walk-through of how all these work/fit together.

Right now am faced with a situation where I run tests and they fail for situations where one test fails because of changes made by another test that precedes it e.g. If am testing a class that views a specific user and a test that deletes that specific user runs first or when creating a user and I have to update the last inserted id(in expected response) every time I run tests.

Also, more examples on this will be of huge help. Thanks, a lot!!

KipchirchirIan commented 4 years ago

I added something to UserCreatorRepositoryTest.php and things seem to be working. I called the setupDatabase() method though I am not sure if it's the best way to go about it.

    /**
     * Test.
     *
     * @return void
     */
    public function testInsertUser(): void
    {
        $this->setupDatabase(); //Method from DatabaseTestTrait

        $repository = $this->createInstance();

        $user = [
            'username' => 'john.doe',
            'email' => 'john.doe@example.com',
            'first_name' => 'John',
            'last_name' => 'Doe',
        ];

        $actual = $repository->insertUser($user);

        $this->assertSame(3, $actual);
    }

I'm assuming I'll have to call the method every time I run tests that need the database although am beginning to think this will result in performance issues.

odan commented 4 years ago

You don't have to call $this->setupDatabase(); manually for each test. Just include the trait DatabaseTestTrait and that's it.

Please take a look at this example:

https://github.com/odan/slim4-skeleton/blob/master/tests/TestCase/Domain/User/Repository/UserCreatorRepositoryTest.php

You can see the @before attribute here. With this attribute Phpunit invokes the setupDatabase before each test. Read more

There is no real performance issue, because the database cleanup is already optimized for performance. Only the changed tables will be truncated.

KipchirchirIan commented 4 years ago

Thank you! Didn't know about annotations.