Created
April 24, 2013 21:31
-
-
Save spirozh/5455741 to your computer and use it in GitHub Desktop.
adaptation of AssertAll from http://blog.drorhelper.com/2011/02/multiple-asserts-done-right.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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