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