1
// ****************************************************************
2
// Copyright 2011, 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
// ****************************************************************
8
using System.Collections;
10
namespace NUnit.Framework.Constraints
13
/// ExactCountConstraint applies another constraint to each
14
/// item in a collection, succeeding only if a specified
15
/// number of items succeed.
17
public class ExactCountConstraint : PrefixConstraint
19
private int expectedCount;
22
/// Construct an ExactCountConstraint on top of an existing constraint
24
/// <param name="expectedCount"></param>
25
/// <param name="itemConstraint"></param>
26
public ExactCountConstraint(int expectedCount, Constraint itemConstraint)
27
: base(itemConstraint)
29
this.DisplayName = "one";
30
this.expectedCount = expectedCount;
34
/// Apply the item constraint to each item in the collection,
35
/// succeeding only if the expected number of items pass.
37
/// <param name="actual"></param>
38
/// <returns></returns>
39
public override bool Matches(object actual)
43
if (!(actual is IEnumerable))
44
throw new ArgumentException("The actual value must be an IEnumerable", "actual");
47
foreach (object item in (IEnumerable)actual)
48
if (baseConstraint.Matches(item))
51
return count == expectedCount;
55
/// Write a description of this constraint to a MessageWriter
57
/// <param name="writer"></param>
58
public override void WriteDescriptionTo(MessageWriter writer)
60
switch (expectedCount)
63
writer.WritePredicate("no item");
66
writer.WritePredicate("exactly one item");
69
writer.WritePredicate("exactly " + expectedCount.ToString() + " items");
73
baseConstraint.WriteDescriptionTo(writer);