I find the concept of partitioning the statements of my unit tests as suggested in the AAA pattern useful.
I tend to add heading comments so that the tests look like this:
// Arrange
int a = 1;
int b = 2;
// Act
int c = a + b;
// Assert
Assert.AreEqual(3, c);
But I am curious, is it normal to always include these header comments?
...or is this something which I should avoid?
int a = 1;
int b = 2;
int c = a + b;
Assert.AreEqual(3, c);
The AAA pattern is a pattern for structuring tests. It breaks each test down into three parts – Arrange, Act, and Assert – where each part is a step leading to the next. The arrange step sets up the test's input values. The act step prompts the primary function being tested.
The AAA (Arrange, Act, Assert) pattern is a common way of writing unit tests for a method under test. The Arrange section of a unit test method initializes objects and sets the value of the data that is passed to the method under test. The Act section invokes the method under test with the arranged parameters.
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.
That doesn't seem to add much value once the basic premise is understood. Since you mention C#, I suggest taking a look at The Art of Unit Testing for examples. Naming a unit test correctly is more important IMHO than arrange/act/assert comments within it. As the book points out, when a test fails, if it is named well you can often deduce the cause of a regression directly if you know what changes were made recently.
I've gotten a lot of value out of doing this. It (to me) looks cleaner, is immediately clear which parts of the test are doing what, and it somewhat enforces the pattern. So no, I don't think you need to avoid it.
If your tests are getting really complicated that's a separate issue. Even a six line test can benefit from those comments. If you have no assert section because you're checking that an exception is thrown, then obviously don't include the assert
comment.
I'm always thankful to have those in code that I'm reviewing, particularly for integration tests. I feel it saves me time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With