Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Contract.Assert throw an exception rather than display a Dialog box

If I'm using the new Code Contracts Contract.Assert method, is it possible to make it throw an exception rather than display a dialog box? I want to do this when running unit tests on the build machine.

like image 995
Nick Randell Avatar asked Jun 24 '11 06:06

Nick Randell


1 Answers

Thanks to this post on MSDN forums I've found a possible solution.

namespace QuickGraph.Tests  
{  
    [TestClass]  
    public class AssemblyContextTest  
    {  
        [AssemblyInitialize]  
        public static void Initialize(TestContext ctx)  
        {  
            // avoid contract violation kill the process  
            Contract.ContractFailed += new EventHandler<ContractFailedEventArgs>(Contract_ContractFailed);  
        }  

        static void Contract_ContractFailed(object sender, System.Diagnostics.Contracts.ContractFailedEventArgs e)  
        {  
            e.SetHandled();  
            Assert.Fail("{0}: {1} {2}", e.FailureKind, e.Message, e.Condition);  
        }  
    }  
}  

This appears to work.

like image 147
Nick Randell Avatar answered Nov 09 '22 21:11

Nick Randell