Unit tests principles
FIRST principle
FIRST principles of testing stand for:
Fast - The developer shouldn’t hesitate to run the unit tests at any point of their development cycle, even if there are thousands of unit tests. They should run and show you the desired output in a matter of seconds
Isolated/Independent - For any given unit test, for its environment variables or for its setup. It should be independent of everything else should so that its results are not influenced by any other factor.
Repeatable - tests should be repeatable and deterministic, their values shouldn’t change based on being run on different environments. Each test should set up its own data and should not depend on any external factors to run its test.
Self-validating - you shouldn’t need to check manually, whether the test passed or not.
Thorough - should fulfill the following conditions:
should cover all the happy paths
try covering all the edge cases, where the author would feel the function would fail.
test for illegal arguments and variables.
test for security and other issues
test for large values, what would a large input do their program.
should try to cover every use case scenario and not just aim for 100% code coverage.
AAA (Arrange-Act-Assert) pattern
The AAA (Arrange-Act-Assert) pattern has become almost a standard across the industry. It suggests that you should divide your test method into three sections: arrange, act and assert. Each one of them only responsible for the part in which they are named after.
In Arrange section you only have code required to setup that specific test. Here objects would be created, mocks setup (if you are using one) and potentially expectations would be set.
Then there is the Act, which should be the invocation of the method being tested.
And on Assert you would simply check whether the expectations were met.
GWT (Given-When-Then) pattern
The essential idea is to break down writing a scenario (or test) into three sections:
The given part describes the state of the world before you begin the behavior you're specifying in this scenario. You can think of it as the pre-conditions to the test.
The when section is that behavior that you're specifying.
Finally the then section describes the changes you expect due to the specified behavior.
Last updated
Was this helpful?