PageRenderTime 26ms CodeModel.GetById 23ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/src/NUnit/framework/Constraints/PredicateConstraint.cs

#
C# | 55 lines | 29 code | 7 blank | 19 comment | 1 complexity | 008f033be862008930bf626f76843742 MD5 | raw file
 1// ****************************************************************
 2// Copyright 2009, 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
 7#if NET_2_0
 8using System;
 9using System.Collections.Generic;
10
11namespace NUnit.Framework.Constraints
12{
13    /// <summary>
14    /// Predicate constraint wraps a Predicate in a constraint,
15    /// returning success if the predicate is true.
16    /// </summary>
17    public class PredicateConstraint<T> : Constraint
18    {
19        Predicate<T> predicate;
20
21        /// <summary>
22        /// Construct a PredicateConstraint from a predicate
23        /// </summary>
24        public PredicateConstraint(Predicate<T> predicate)
25        {
26            this.predicate = predicate;
27        }
28
29        /// <summary>
30        /// Determines whether the predicate succeeds when applied
31        /// to the actual value.
32        /// </summary>
33        public override bool Matches(object actual)
34        {
35            this.actual = actual;
36
37            if (!(actual is T))
38                throw new ArgumentException("The actual value is not of type " + typeof(T).Name, "actual");
39
40            return predicate((T)actual);
41        }
42
43        /// <summary>
44        /// Writes the description to a MessageWriter
45        /// </summary>
46        public override void WriteDescriptionTo(MessageWriter writer)
47        {
48            writer.WritePredicate("value matching");
49            writer.Write(predicate.Method.Name.StartsWith("<")
50                ? "lambda expression"
51                : predicate.Method.Name);
52        }
53    }
54}
55#endif