PageRenderTime 47ms CodeModel.GetById 25ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

/src/NUnit/framework/Constraints/ThrowsConstraint.cs

#
C# | 195 lines | 103 code | 22 blank | 70 comment | 18 complexity | 292da6c21f5c9f7c96db957b8e639903 MD5 | raw file
  1// ****************************************************************
  2// Copyright 2008, Charlie Poole
  3// This is free software licensed under the NUnit license. You may
  4// obtain a copy of the license at http://nunit.org
  5// ****************************************************************
  6
  7using System;
  8
  9namespace NUnit.Framework.Constraints
 10{
 11    #region ThrowsConstraint
 12    /// <summary>
 13    /// ThrowsConstraint is used to test the exception thrown by 
 14    /// a delegate by applying a constraint to it.
 15    /// </summary>
 16    public class ThrowsConstraint : PrefixConstraint
 17    {
 18        private Exception caughtException;
 19
 20        /// <summary>
 21        /// Initializes a new instance of the <see cref="T:ThrowsConstraint"/> class,
 22        /// using a constraint to be applied to the exception.
 23        /// </summary>
 24        /// <param name="baseConstraint">A constraint to apply to the caught exception.</param>
 25        public ThrowsConstraint(Constraint baseConstraint)
 26            : base(baseConstraint) { }
 27
 28        /// <summary>
 29        /// Get the actual exception thrown - used by Assert.Throws.
 30        /// </summary>
 31        public Exception ActualException
 32        {
 33            get { return caughtException; }
 34        }
 35
 36        #region Constraint Overrides
 37        /// <summary>
 38        /// Executes the code of the delegate and captures any exception.
 39        /// If a non-null base constraint was provided, it applies that
 40        /// constraint to the exception.
 41        /// </summary>
 42        /// <param name="actual">A delegate representing the code to be tested</param>
 43        /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns>
 44        public override bool Matches(object actual)
 45        {
 46            TestDelegate code = actual as TestDelegate;
 47            if (code == null)
 48                throw new ArgumentException(
 49                    string.Format("The actual value must be a TestDelegate but was {0}",actual.GetType().Name), "actual");
 50
 51            this.caughtException = null;
 52
 53            try
 54            {
 55                code();
 56            }
 57            catch (Exception ex)
 58            {
 59                this.caughtException = ex;
 60            }
 61
 62            if (this.caughtException == null)
 63                return false;
 64
 65            return baseConstraint == null || baseConstraint.Matches(caughtException);
 66        }
 67
 68#if NET_2_0
 69        /// <summary>
 70        /// Converts an ActualValueDelegate to a TestDelegate
 71        /// before calling the primary overload.
 72        /// </summary>
 73        /// <param name="del"></param>
 74        /// <returns></returns>
 75        public override bool Matches(ActualValueDelegate del)
 76        {
 77            TestDelegate testDelegate = new TestDelegate(delegate { del(); });
 78            return Matches((object)testDelegate);
 79        }
 80#endif
 81
 82        /// <summary>
 83        /// Write the constraint description to a MessageWriter
 84        /// </summary>
 85        /// <param name="writer">The writer on which the description is displayed</param>
 86        public override void WriteDescriptionTo(MessageWriter writer)
 87        {
 88            if (baseConstraint == null)
 89                writer.WritePredicate("an exception");
 90            else
 91                baseConstraint.WriteDescriptionTo(writer);
 92        }
 93
 94        /// <summary>
 95        /// Write the actual value for a failing constraint test to a
 96        /// MessageWriter. The default implementation simply writes
 97        /// the raw value of actual, leaving it to the writer to
 98        /// perform any formatting.
 99        /// </summary>
100        /// <param name="writer">The writer on which the actual value is displayed</param>
101        public override void WriteActualValueTo(MessageWriter writer)
102        {
103            if (caughtException == null)
104                writer.Write("no exception thrown");
105            else if (baseConstraint != null)
106                baseConstraint.WriteActualValueTo(writer);
107            else
108                writer.WriteActualValue(caughtException);
109        }
110        #endregion
111
112        /// <summary>
113        /// Returns the string representation of this constraint
114        /// </summary>
115        protected override string GetStringRepresentation()
116        {
117            if (baseConstraint == null)
118                return "<throws>";
119            
120            return base.GetStringRepresentation();
121        }
122    }
123    #endregion
124
125    #region ThrowsNothingConstraint
126    /// <summary>
127    /// ThrowsNothingConstraint tests that a delegate does not
128    /// throw an exception.
129    /// </summary>
130	public class ThrowsNothingConstraint : Constraint
131	{
132		private Exception caughtException;
133
134        /// <summary>
135        /// Test whether the constraint is satisfied by a given value
136        /// </summary>
137        /// <param name="actual">The value to be tested</param>
138        /// <returns>True if no exception is thrown, otherwise false</returns>
139		public override bool Matches(object actual)
140		{
141			TestDelegate code = actual as TestDelegate;
142			if (code == null)
143				throw new ArgumentException("The actual value must be a TestDelegate", "actual");
144
145            this.caughtException = null;
146
147            try
148            {
149                code();
150            }
151            catch (Exception ex)
152            {
153                this.caughtException = ex;
154            }
155
156			return this.caughtException == null;
157		}
158
159#if NET_2_0
160        /// <summary>
161        /// Converts an ActualValueDelegate to a TestDelegate
162        /// before calling the primary overload.
163        /// </summary>
164        /// <param name="del"></param>
165        /// <returns></returns>
166        public override bool Matches(ActualValueDelegate del)
167        {
168            TestDelegate testDelegate = new TestDelegate(delegate { del(); });
169            return Matches((object)testDelegate);
170        }
171#endif
172
173        /// <summary>
174        /// Write the constraint description to a MessageWriter
175        /// </summary>
176        /// <param name="writer">The writer on which the description is displayed</param>
177		public override void WriteDescriptionTo(MessageWriter writer)
178		{
179			writer.Write(string.Format("No Exception to be thrown"));
180		}
181
182        /// <summary>
183        /// Write the actual value for a failing constraint test to a
184        /// MessageWriter. The default implementation simply writes
185        /// the raw value of actual, leaving it to the writer to
186        /// perform any formatting.
187        /// </summary>
188        /// <param name="writer">The writer on which the actual value is displayed</param>
189		public override void WriteActualValueTo(MessageWriter writer)
190		{
191			writer.WriteActualValue( this.caughtException.GetType() );
192		}
193    }
194    #endregion
195}