Back to the basics: Tests, part 4
If tests are code, organizing them are extremely important. thinking about files organization, the most two common approach are:
- My file, my test: The test file stays side a side from the original code, normally only differentiate by the extension.
- The test project: A "folder test" that replicate the original project structure, brings the same file as their tests representations.
Tests normally allow a lot of sublevels in details, like a general descriptions and tests cases, you can get this pattern to easily categorize the tests and get a better representation of what the test is, what does, and where, like:
The object to test
The test case premise
The case
The case
The case
The test case premise
The case
The case
When we are written the actual test, a good way to organize it is using the AAA Pattern: Arrange, Act, and Assert.
This pattern is very common way to easily identify the dependencies that the test uses, the original functions, and what we need to assert, for example a class that have a sum method, the organization will become:
Arrange -> new ClassToTest
Act -> objToTest.sum(1,1)
Assert -> result must be 2
To test the method, we obligatory need to instantiate the class, so we arrange the object to have access to the method, if the constructor need something, this part if where we will create the dependencies etc.
The act session, is where we call the actual method to the code to generate the artifact that we want to check, in our case, basically call the sum method.
Be the end, we came to the assert session, where we will check if the results are the expected.
A lot of times, you will see a lot of code repetition between the tests cases to arrange, act and assert. To solve it, a lot of tests frameworks have hooks to facilitate the test creation and reduce this boilerplate.
The most common hooks are:
- Setups: Code that run before anything, this normally is used to set something in common to all tests.
- Before all: Normally applied to a test section, guarantee that run before the section.
- Before each: Normally applied to a test section, guarantee that run before each item in the section.
- After each: Normally applied to a test section, guarantee that run after each item in the section.
- After all: Normally applied to a test section, guarantee that run after the section.
- Cleanings: Code that run after everything, this normally is used to set end the test battery.
Hooks are pretty good to maintain the code clean, but if abused can generate a confusion, so let's see some good practices to write tests in the next one!