1 // ***********************************************************************
2 // Copyright (c) 2007 Charlie Poole
4 // Permission is hereby granted, free of charge, to any person obtaining
5 // a copy of this software and associated documentation files (the
6 // "Software"), to deal in the Software without restriction, including
7 // without limitation the rights to use, copy, modify, merge, publish,
8 // distribute, sublicense, and/or sell copies of the Software, and to
9 // permit persons to whom the Software is furnished to do so, subject to
10 // the following conditions:
12 // The above copyright notice and this permission notice shall be
13 // included in all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 // ***********************************************************************
25 #define NUNIT_FRAMEWORK
30 using System.Reflection;
31 using NUnit.Compatibility;
33 namespace NUnit.Framework.Constraints
36 /// PropertyExistsConstraint tests that a named property
37 /// exists on the object provided through Match.
39 /// Originally, PropertyConstraint provided this feature
40 /// in addition to making optional tests on the value
41 /// of the property. The two constraints are now separate.
43 public class PropertyExistsConstraint : Constraint
45 private readonly string name;
50 /// Initializes a new instance of the <see cref="PropertyExistsConstraint"/> class.
52 /// <param name="name">The name of the property.</param>
53 public PropertyExistsConstraint(string name)
60 /// The Description of what this constraint tests, for
61 /// use in messages and in the ConstraintResult.
63 public override string Description
65 get { return "property " + name; }
69 /// Test whether the property exists for a given object
71 /// <param name="actual">The object to be tested</param>
72 /// <returns>True for success, false for failure</returns>
73 public override ConstraintResult ApplyTo<TActual>(TActual actual)
75 Guard.ArgumentNotNull(actual, "actual");
77 actualType = actual as Type;
78 if (actualType == null)
79 actualType = actual.GetType();
81 PropertyInfo property = actualType.GetProperty(name,
82 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
83 return new ConstraintResult(this, actualType, property != null);
87 /// Returns the string representation of the constraint.
89 /// <returns></returns>
90 protected override string GetStringRepresentation()
92 return string.Format("<propertyexists {0}>", name);