// Embarrassingly poor example of using Verify semantics in MsTest // // Use at your own risk! // // Author: Grey Ham(28 December 2011) - www.havecomputerwillcode.com/blog // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace HaveCompTest { // Might as well derive from the unit test exception baseclasses... public class MyVerifyWrapperException : UnitTestAssertException { // Pass in the original validation exception public MyVerifyWrapperException(UnitTestAssertException utex, string spoofedStackTrace) { OriginalException = utex; SpoofedStackTrace = spoofedStackTrace; } public override System.Collections.IDictionary Data { get { return this.OriginalException.Data; } } public override string Message { get { return OriginalException.Message; } } public override string Source { get { return OriginalException.Source; } } public override string StackTrace { get { return SpoofedStackTrace; } } public readonly System.Exception OriginalException; public readonly string SpoofedStackTrace; } public class Verify { public Verify() { Exceptions = new List(); } public void AreEqual(int left, int right) { try { Assert.AreEqual(left, right); } catch (UnitTestAssertException ex) { string[] delims = new string[] { "\r\n" }; // So we give correct feedback in TRIX, we need to unwind the stack to get to where the Verify method was called... List t = new List(Environment.StackTrace.Split(delims, StringSplitOptions.None)); t.RemoveRange(0, 3); string stack = String.Join("\r\n", t); MyVerifyWrapperException e = new MyVerifyWrapperException(ex, stack); Exceptions.Add(e); } } public readonly List Exceptions; } [TestClass] public class VerifyTest { public TestContext TestContext { get; set; } private Verify Verify; [TestInitialize] public void Initialize() { Verify = new Verify(); } [TestCleanup] public void Cleanup() { if (TestContext.CurrentTestOutcome == UnitTestOutcome.Passed) { if (Verify.Exceptions.Count() > 0) { throw Verify.Exceptions.First(); } } else { } } [TestMethod] public void Pointless() { Verify.AreEqual(1, 2); Verify.AreEqual(3, 3); Verify.AreEqual(3, 4); } } }