Test, Refactor, Document
Now comes the (+3) step. This step assumes that your API is already working and that you want to make sure your API is more bullet-proof. Note that although I consider this optional, I personally almost always will test, refactor, and document my code if I have the time.
Test
If you write tests, it's like little robots that you build that do things for you instead of clicking
-Jeffrey Way, Creator of laracasts.com
There are many levels to testing, here are a couple:
Unit Tests
Integration Tests
End-to-end Tests
User Acceptance Tests
Load/Performance Tests
There are many different ways to test our code, but I believe the two most important types of tests that we should write are unit and integration tests.
Unit tests are low level tests that test functions in the code. One of the main advantages for using the layered architecture is for us to have the ability to intricately test each component of each layer. You will see in the later chapters just how much layered architecture shines and how easy it is to write isolated tests.
The second type of tests that we'll be writing are high level integration tests. These types of tests are tests that simply call the API to check the response output and the database (if necessary). These are my favorite types of tests to write because these tests are essentially a simulation of how a developer would do to call your API.
The AAA Framework
If you have not written many tests before, here is the framework that most developers follow. It's called the Arrange, Act, and Assert Framework. Here's a quick example of how we might want to plan our test cases.
Arrange
Setup the world; database
Setup mocks
Act
Call the function, or
Call the API
Assert
Validation checks
Database has been updated
Output response of our endpoint
You will see more of this later as we go in depth into testing an endpoint from starting to finish in both unit and integration testing.
Refactor
Unfortunately refactoring is way beyond the scope of this book, but it is always something to consider when writing code.
For those that wants to look more into refactoring, I recommend the following two pieces of literature:
We will be refactoring our code, make sure to read the bonus chapter of this book, Refactoring to HATEOAS, as we refactor our code to make it hypermedia-friendly.
Document
We will be following the OpenAPI specification, and we'll be using Swagger as our tool for documenting all of our API endpoints.
Needless to say, documentation is extremely important, especially if you are working in a team.
Last updated