ContainsConstraint
ContainsConstraint tests a whether a string contains a substring
or a collection contains an object. It postpones the decision of
which test to use until the type of the actual argument is known.
This allows testing whether a string is contained in a collection
or as a substring of another string using the same syntax.
using System;
using System.Runtime.CompilerServices;
namespace NUnit.Framework.Constraints
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class ContainsConstraint : Constraint
{
[System.Runtime.CompilerServices.Nullable(2)]
private readonly object _expected;
[System.Runtime.CompilerServices.Nullable(2)]
private Constraint _realConstraint;
private bool _ignoreCase;
private bool _ignoreWhiteSpace;
public override string Description {
get {
if (_realConstraint != null)
return _realConstraint.Description;
string text = "containing " + MsgUtils.FormatValue(_expected);
if (_ignoreCase)
text += ", ignoring case";
return text;
}
}
public ContainsConstraint IgnoreCase {
get {
_ignoreCase = true;
return this;
}
}
public ContainsConstraint IgnoreWhiteSpace {
get {
_ignoreWhiteSpace = true;
return this;
}
}
[System.Runtime.CompilerServices.NullableContext(2)]
public ContainsConstraint(object expected)
: base(Array.Empty<object>())
{
_expected = expected;
}
public override ConstraintResult ApplyTo<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual)
{
if (((object)actual) is string) {
string text = _expected as string;
if (text == null)
throw new InvalidOperationException("Expected value for substring must be a string. Suggest using Contains.Substring to get a compile time error");
StringConstraint stringConstraint = new SubstringConstraint(text);
if (_ignoreCase)
stringConstraint = stringConstraint.IgnoreCase;
if (_ignoreWhiteSpace)
throw new InvalidOperationException("IgnoreWhiteSpace not supported on SubStringConstraint");
_realConstraint = stringConstraint;
} else {
EqualConstraint equalConstraint = new EqualConstraint(_expected);
if (_ignoreCase)
equalConstraint = equalConstraint.IgnoreCase;
if (_ignoreWhiteSpace)
equalConstraint = equalConstraint.IgnoreWhiteSpace;
_realConstraint = new SomeItemsConstraint(equalConstraint);
}
return _realConstraint.ApplyTo(actual);
}
}
}