Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 616
Lea Hayes Avatar asked Sep 06 '14 06:09

Lea Hayes


People also ask

What should happen in the ACT section of a unit test according to AAA?

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.

What is arrange Act assert testing?

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.

What are the three essential A's related to unit testing?

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.


Video Answer


2 Answers

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.

like image 187
bright Avatar answered Sep 28 '22 03:09

bright


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.

like image 27
b15 Avatar answered Sep 28 '22 01:09

b15