DEV Community

Cover image for Our way: Tests
Robson Tenório
Robson Tenório

Posted on • Edited on

Our way: Tests

👉 Go to Summary

There is no wrong or right way, there is our way.

-- Someone

.
.
.

The coverage test trap

  1. The 100% coverage does not mean anything by itself.
  2. You have to be confident.
  3. You have to be confident.
  4. You have to be confident.
  5. Yes, 3 times.
  6. Are you really testing what matters? Double check it.

Test what matters

  1. Test only your business rule.
  2. You don't need to test what is backed by Laravel.
  3. Rule of thumb: if you mutated data you need to test it!
// You have a business rule here to test
// You must assure that aged people need assistance, by default!


public function save(Request $request) 
{    

    $data = $request->validate(...);


    if ($data['age'] > 60) {
        $data['need_assistance'] = true;
    }

    User::create($data);

}
Enter fullscreen mode Exit fullscreen mode
// You have a business rule here to test
// After creating an user, you have insert data in another table


public function save(Request $request) 
{    

    $data = $request->validate(...);

    User::create($data);

    Invite::create([something will be created here])

}
Enter fullscreen mode Exit fullscreen mode

Basics

  1. Get green is not enough, get confident.
  2. Test behavior (input/output), not implementation details (mocks).
  3. Test’s name is important.
  4. Write comments before writing test (GIVEN, WHEN, THEN).
  5. Complex features can have more than one test class.

// I don't give a shit how avatar was generated!
// I just wanna see the avatar !

class CreateAvatarTest extends TestCase {

    public function test_create_online_user_avatar()
    {
        // GIVEN there is a user
        $user = UserFactory::new()->create();

        // WHEN I request to make an avatar
        $response = $this->get("/avatar-maker?for={$user->id}")

        // THEN I get avatar's URL
        $response->assertJsonFragment(['url' => 'https://...']);

    }    
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)