Skip to content

Instantly share code, notes, and snippets.

@DominicFinn
Created April 23, 2013 08:33
Show Gist options
  • Save DominicFinn/5441803 to your computer and use it in GitHub Desktop.
Save DominicFinn/5441803 to your computer and use it in GitHub Desktop.
A way to test multiple assertions in the same method but not fail on the first assertion so you have an overview of what failed. Note, this is not my ideal situation, just a proof of concept.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace TestWithExceptions
{
/// <summary>
/// Note: Not recommended, use a method per assertion ideally. This is just out of interest...
/// </summary>
[TestFixture]
public class Test : Specification
{
[Test]
public void TestMultipleAssertions()
{
Assert.IsTrue(this.AssertAll(new List<Action>()
{
() => Assert.AreEqual(1, 3),
() => Assert.AreNotSame(1, 3),
() => Assert.AreEqual("Cat", "Dog")
}));
}
}
public class Specification
{
public bool AssertAll(IList<Action> assertions)
{
var assertionExceptions = this.CheckAssertions(assertions);
if (!assertionExceptions.Any()) return true;
var exceptionBuilder = new StringBuilder();
foreach (var ex in assertionExceptions)
{
exceptionBuilder.AppendLine(ex.Message);
}
throw new AssertionException(exceptionBuilder.ToString());
}
public IList<AssertionException> CheckAssertions(IList<Action> assertions)
{
var failedAssertions = new List<AssertionException>();
foreach (var action in assertions)
{
try
{
action();
}
catch (AssertionException ex)
{
failedAssertions.Add(ex);
}
}
return failedAssertions;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment