Skip to content

Instantly share code, notes, and snippets.

@spirozh
Created April 24, 2013 21:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spirozh/5455741 to your computer and use it in GitHub Desktop.
Save spirozh/5455741 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SomeNamespace
{
/// <summary>
/// Check and report multiple conditions in unit tests.
///
/// Adapted from: http://blog.drorhelper.com/2011/02/multiple-asserts-done-right.html
/// </summary>
public class AssertAll
{
public static void Execute(params Action[] assertionsToRun)
{
var errorMessages = new List<Exception>();
foreach (var action in assertionsToRun)
{
try
{
action.Invoke();
}
catch (Exception exc)
{
errorMessages.Add(exc);
}
}
if (errorMessages.Count <= 0)
return;
var errorText = new StringBuilder();
foreach (Exception e in errorMessages)
{
if (errorText.Length > 0)
errorText.Append(Environment.NewLine);
errorText.Append(digestStackTrace(e));
}
Assert.Fail(string.Format("{0}/{1} conditions failed:{2}{2}{3}", errorMessages.Count, assertionsToRun.Length,
Environment.NewLine, errorText));
}
/// <summary>
/// Remove boring lines in stack trace, where boring is a line either in the Execute method of this class
/// or anything in the Microsoft.VisualStudio.TestTools.UnitTesting package.
/// </summary>
private static object digestStackTrace(Exception e)
{
if (e is UnitTestAssertException)
{
var sb = new StringBuilder(e.Message).AppendLine();
foreach (var line in e.StackTrace.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries))
{
// don't report uninteresting stack trace lines.
if (line.Contains("Microsoft.VisualStudio.TestTools.UnitTesting") || line.Contains("AssertAll.Execute"))
continue;
sb.AppendLine(line);
}
return sb;
}
return e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment