When writing my unit tests I typically use the AAA(Arrange-Act-Assert) pattern. This pattern splits a test in 3 sections:
- 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 Assert section verifies that the action of the method under test behaves as expected.
Here is an example from one of my projects using XUnit:
And if it’s a test that expects an exception I use the Assert.Throws
method:
What I don't like in the example, above is that it violates the AAA pattern. The Assert is already happening in the Act part.
While reviewing some code from one of my team members, I noticed he used the following approach to split out the Act and Assert part when using Assert.Throws
:
He is using a Local Function to create this separation. Nice!