1 – Test business rules from your methods
Well, what should be tested? Business rules, for sure! Don’t implement unitary tests to cover all methods and create numbers, make a real test!
Know your method and test it with meaningful flows where you can guarantee your logic is working.
Don’t implement meaningless tests.
2 – Give a clear, meaningful name to your method
Think about a great name for your test and choose the name that represents what you are testing.
Bad example:
@Test public void test1()
Good example:
@Test public void checkIfCustomerIsBlockedByFraudTest()
Much easier to understand, huh? You know your method is checking if the customer is blocked by fraud.
3 – If your method is too complex, use TDD (Test Driven Development)
Have you ever had to implement a very complex method? If so, it’s very difficult to test, right? To make implementation easier you should use TDD and implement your test before implementing your method. Use baby steps, do the simplest thing first and then make your test work! Then keep going until your method is completely implemented!
The cool thing about using TDD is that your code is already tested! It’s amazing how it can help you! Just practice it, and see how amazing this is!
4 – Create your classes/methods with cohesion
Unitary tests help a lot to know if your code is good or bad. It’s very simple if you can’t test your code easily, your code doesn’t have cohesion or low coupling.
If you are in this situation, refactor your code, don’t turn it into a big problem. If your code keeps on growing like this, you will have real problems changing features or implementing something new.
If you implement a test for a method that is responsible for many actions, it will be completely useless. Anything you change on your method can break the test.
Avoid unnecessary stress by just refactoring your code.
5 – Know the difference between Unitary Tests and Integration Tests
What is the difference? Easy! Unitary Tests evaluate just one method. They test your code unitarily, method by method. You won’t use information from the database. You will “Mock” data, meaning you will create your own “fake” data to implement the test you need for your business rule. Although you can’t interact with the database, Unitary Tests are very fast and it’s possible to test business rules effectively.
Integrated tests, as the name says, are more complete tests. You will interact with the database. You will insert your own data into the database and test your services integrally. The cons are that it is slow, and it takes time to test everything. You also take more time to implement the test. It’s necessary to create your own data directly in the database (insert script, delete script).