Do you know how to structure a unit test (aka the 3 a's)?

Last updated by Steven Qiang [SSW] over 1 year ago.See history

A test verifies expectations. Traditionally it has the form of 3 major steps:

  1. Arrange
  2. Act
  3. Assert

In the "Arrange" step we get everything ready and make sure we have all things handy for the "Act" step.

The "Act" step executes the relevant code piece that we want to test.

The "Assert" step verifies our expectations by stating what we were expecting from the system under test.

Developers call this the "AAA" syntax.

public void TestRegisterPost_ValidUser_ReturnsRedirect()
   // Arrange
   AccountController controller = GetAccountController();
   RegisterModel model = new RegisterModel()
      UserName = "someUser",
      Email = "goodEmail",
      Password = "goodPassword",
      ConfirmPassword = "goodPassword"
   // Act
   ActionResult result = controller.Register(model);
   // Assert
   RedirectToRouteResult redirectResult = (RedirectToRouteResult)result;
   Assert.AreEqual("Home", redirectResult.RouteValues["controller"]);
   Assert.AreEqual("Index", redirectResult.RouteValues["action"]);

Figure: A good structure for a unit test

We open source. Powered by GitHub