Are heading comments recommended when unit testing with Arrange-Act-Assert?

3.8k Views Asked by At

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);
2

There are 2 best solutions below

0
bright On BEST ANSWER

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.

1
b15 On

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.