Coding Practice: Unit Testing – Arrange, Act, Assert

Coding Practice: How should I layout my unit tests?
Just as you   would when working with any code, your objective is readability and ease of   comprehension.  A coding layout for unit tests that achieves this   objective is the Arrange, Act, Assert pattern: Arrange all necessary   preconditions and inputs, Act on the object or method under test, and Assert   that the expected results have occurred.

“If you have too much code in any of these sections,   you’re probably breaking good unit test best practices by: having too much setup, testing too many concerns, or having too many assertions.”
–            Jag   Reehal

When you use   tools like mocking, your unit test setup becomes more involved (see   below).  The power of Arrange, Act, Assert is that it will make sure   that the behavior you are validating is clear.  This is important   because the quickest way for someone to familiarize themselves with your code   is to review your unit tests, and the easier they are to understand the   faster someone can ramp up on your code base.

        public void Will_Write_To_Log_If_Customer_Fails_Validation_When_Adding_Customer()
            //   Arrange
            var customerValidator = new Mock();
            customerValidator.Setup(c => c.IsValid(It.IsAny()))
                 .Throws(new ArgumentException(CustomerValidator.NAME_ERROR_MESSAGE));

            var logger = new Mock();
            var customerService = new CustomerService(customerValidator.Object, logger.Object);

            //   Act
            customerService.AddCustomer(new Customer());

            // Assert
            logger.Verify(c => c.LogError(CustomerValidator.NAME_ERROR_MESSAGE));


About Chris VanHoose

Principal Software Architect at CT Lien Solutions
This entry was posted in Software Architecture and tagged , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.