Java Shot #3: Document Arrange, Act and Assert sections while writing Unit tests
A unit test can be broken down into three segments.
- Arrange
- Act and
- Assert
In Arrange step, you would build the necessary data that is needed for execution of the test case along with that you can also setup Mock functionality.
In the Act step, you will actually call the method that needs to be tested.
In the Assert step, you would validate the actual response values with the expected response values.
Presence of these three segments is something known to majority of the engineers who write test cases frequently - even engineers who wrote test cases once or twice, would have written the test cases following the arrange-act-assert pattern.
As a best practice, I recommend adding a comment at the start of each segment to denote the beginning of that segment.
Sample Java code without Arrange-Act-Assert documentation 😦
If you see in the above code, it's quite complicated to understand where the each section ends.
Sample Java code without Arrange-Act-Assert documentation and newline between sections 🙂
You can add newline to specify the sections but it's not explicitly clear what's the importance of the newline.
To be more explicit, you can add a comment and that makes a lot of difference.