Write Unit Tests for your Rest APIs
I want to detail the steps that I try to take when creating a new endpoint in a backend project (Java, SpringBoot, Mockito). Definitely this is not the same all the time, but that’s not the topic for this post.
Our task is: implement a new endpoint that retrieves all the products that exist at the moment.
-> create a new method in the service class that retrieves using persistence layer (no queries - -allowed here) all the products available
-> create endpoint that calls the above service method and returns data
-> create unit test for service method
-> create integration test for the new endpoint
This is my way of testing, you can mix the points as you like. We are decoupling the persistence (VendorProductRepository) and business(VendorProductService) layers.
This is the actual endpoint, which has one liner in this case. It simply returns the result of the service call.
This unit test describes the ‘given’ - ‘when’ - ‘then’. We create a dummy object which we add to a list. The given part is when we describe(stub) what code will do when the repository is asked to return all products. The when part is when we call the service method, and the then part is when we verify the mocked service call returns the initially given list.
This integration test, describes the happy path for retrieving a list of all available products. It hits the database so it’s best to be made on a developer version of it. We make the Http call and check against the HttpStatus response and body.
This is when I feel more confident adding a new endpoint to do something will actually work. This code is actually part of my #twiliohackathon project, so the code is public here
Notes mentioning this note
There are no notes linking to this note.