如何为这种情况编写一个好的测试单元/功能测试

This thread is more about the idea, not giving ready code.

I'm currently making Dusk (Selenium implemented in Laravel) tests for an application. I have functionality which is returning:

Search users which like color blue.

It's of course a bit more complicated (relations, many models, etc.). I wrote two tests right now.

  • Searching for users who likes color abc. Only my test users like it, so I know what result I should get. I am doing comparison between db query and int.

  • Searching for users who likes color (random from available colors) in the database. It's the same logic as previous with a real color name.

I think that it's not good, because I never know what result I should get from the database. Checking manually in the database is hard with large amount of users.

I am asking for some ideas how and what I should test to be sure that functionality returns correct result.

The best way for me is to have a clean database before each test. Then you can add data you need for a particular test.

So your test should look like:

class SearchUserTest extends TestCase
{
    // Refresh migrations before each test
    use RefreshDatabase;

    public function testCanFindUsersThatLikeSomeColor()
    {
        // Arrange
        // Create $user1 who likes color blue
        // Create $user2 who likes color green
        // Create $user3 who doesn't like any color

        // Act
        // Make your search request to find users who like color blue

        // Assert
        // Assert response has $user1 and doesn't have $user2 and $user3

    }

}