History of the question:
The Arrange-Act-Assert (AAA) pattern was proposed to simplify the structure of tests and improve their readability. It is actively used in modern testing frameworks and is a de facto standard when writing automated tests of any kind.
The problem:
Without a clear structure, test cases become bulky, hard to read, and difficult to maintain. There is confusion between data setup, invocation of the behavior being tested, and verification of the result. This leads to technical debt and errors in tests.
The solution:
Strictly adhere to the AAA pattern when writing a test.
Key features:
Can the AAA sequence be broken if the test seems obvious?
Usually not. Any deviation from the AAA structure reduces the readability of the test for other developers and makes it vulnerable to errors during maintenance.
Is it acceptable to combine Act and Assert into one expression for short tests?
It's better to avoid this, as it complicates understanding and possible extension of the test in the future.
Should data cleanup logic be included in the Arrange stage?
No. Cleanup or Teardown is usually implemented in separate methods, for example, in testing framework hooks (After, AfterEach).
A test for adding a record to the database first checks and only then adds it. A random assert in the middle causes issues.
Pros:
Cons:
The test begins with data cleanup, then proceeds to adding a record, and only afterward checks the result, strictly following AAA.
Pros:
Cons: