How am I learning TDD?
When we are writing a new software we want to ensure that the code has quality and meets the customer expectations, that's the reason I want to talk a little bit about Test Driven Development.
I have to say that I'm changing the behavior when I write new code, I'm still learning about TDD so here is what I've to say about it:
- TDD will help us to minimize the bugs in the code
- TDD will allow us to meet the customer specifications
- With TDD we are writing modular and testable code
- With TDD we think first in the test cases that our code needs to handle
Before knowing about TDD I used to write the code and then write tests to validate that code, but now I changed this with next steps:
- Write code with no implementation at all
- Write test cases
- Run test cases (test cases will fail)
- Write implementation for classes/methods (test cases must pass)
- Refactor the code (improve implementations)
For this example I'll take next repo from github test-application
In order to write a test, let's imagine that the requirement is: and endpoint to create new customers, and the email should be unique for each client and the customer name should not be empty.
In the next image we can see the sequence required to create a new customer.
As you can see in the diagram we are using three layers: controller, service and repository and of course a mapper that will convert the object between the entity and view.
The first step will be create the mapper without implementation and write the required tests, then we will see how the test are failing and after that we must fix all the tests adding new code to our mapper.
- Customer Mapper
- Customer Mapper Test:
The test cases I'm thinking on are: when entity/view are invalid and when are valid parameters
- Run test
- Implement code to fix test cases
Of course we can add more and more test cases and improve the implementation, that it is your homework, now lets write test cases for our service, in this case we are going to use mocking, remember that we need to test every layer in isolated way.
- Empty Service
- Test Cases for validation
- Code implemented to fix test cases
- Write test cases for save method
- Code implemented to fix test cases for save method
That's it, now we have mapper and service layer with unit testing, with the previous examples you can add unit testing for controller, you may want to see the git repository and do better implementations and test cases.
Thanks for reading
vcg