Skip to main content

A wrapper that takes an array of actions to invoke, which in turn catches exceptions to report back after all other actions have been invoked.

// Multiple asserts in a unit test

public class AssertAll
{
    public static void Execute(params Action[] assertionsToRun)
    {
        List<exception> errorMessages = new List<exception>();
        foreach (var action in assertionsToRun)
        {
            try
            {
                action.Invoke();
            }
            catch (Exception exc)
            {
                errorMessages.Add(exc);
            }
        }

        if (errorMessages.Count > 0)
        {
            var separator = string.Format("{0}{0}", Environment.NewLine);
            string errorMessageString = string.Join(separator, errorMessages);

            Assert.Fail(string.Format("The following conditions failed:{0}{1}",
                                      Environment.NewLine, errorMessageString));
        }
    }
}

// Usage:
// -------------------------------------------------------------------------

[TestMethod]
public void SimpleTest2()
{
    var result = 2 + 2;

    AssertAll.Execute(
        () => Assert.IsInstanceOfType(result, typeof(double)),
        () => Assert.AreEqual(4, result));
}