Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API Unit Testing (Test Endpoints vs. Test Everything)

we are building an API using Laravel, and we are facing an essential question:

Are we supposed to test everything (every method in every Model, Controller, and any other class)? or just test the API endpoints since testing endpoints means that everything else will be tested, because an API endpoint is using a Controller's method, that is in turn using a Model's method!

In fact I tend to the later one which is testing endpoints will help you test everything else, but I need to be sure that this is the right thing to do.

Edit:

Consider the following two points:

  • testing endpoints means that I have to send an HTTP request and wait for the response to see if it is what I need, and that may be very bad con for this method.
  • testing everything means that I have to find some way to mock up laravel request and its headers, and that may be very bad con for this method.

Any hints or comments will be appreciated.

like image 718
Ahmad Hajjar Avatar asked Mar 04 '15 09:03

Ahmad Hajjar


1 Answers

Arguments and supporters exist for both sides. I suspect there are as many opinions on this subject as there are developers doing any form of developer testing.

In a nutshell:

  • Unit tests put greater pressure on your design. Bad code will hurt more if you are testing at the unit level.
  • Unit tests allow you to pinpoint problems more accurately, since they test each unit of work in isolation. If a unit test fails, you know where to look for the problem. If an integrated test blows up, you know something's wrong but typically have to start debugging to find the actual problem.

I like the phrase twitter user @everzet recently used:

When they're green, all tests look the same. It's when they're red you see the real difference.

On the other hand, integrated tests provide more freedom when refactoring. If you test only at the API level, you can change the entire implementation without affecting your tests. If you test at the unit level, a refactoring might mean you have to update/rewrite a whole lot of tests.

like image 184
prgmtc Avatar answered Oct 09 '22 00:10

prgmtc