nunit
nunit copied to clipboard
Collection constraint for strict superset/subset
Hi there,
I am using NUnit 3.13.3 and I am trying to write a constraint to assert that a collectionB contains all elements of collectionA plus one or more extra elements.
I see NUnit has the CollectionSubsetConstraint and the CollectionSupersetConstraint. So, I suppose I could write something like that:
[Test]
public void TestStrictSupersetOf()
{
var collA = new int[] {0};
var collB = new int[] {0, 1};
Assert.That(collB, Is.SupersetOf(collA).And.Not.EquivalentTo(collA));
}
But are there constraints for strict subsets and strict supersets? Or would that be a new constraint?
Another possibility would be a "Has.More.Items.Than", assuming we just want to check the item count. Is there such a constraint?
Kind regards, Reureu
Thanks for your question @reureu .
There's no current explicit support for strict superset/subset to my knowledge in a single operation, though as you say it's possible to emulate the functionality by combining multiple constraints together like your example of Is.SuperSetOf().And.Not.EquivalentTo()
.
The downside of this is that each constraint resolves independently which would mean the work (and time taken) is duplicated. NUnit tries to make each of these operations efficient, but there could be undesireable performance impacts if dealing with two large non-homogeneous sets. While I'm not sure how common that scenario is, I'd be curious to see what others think about adding explicit support for strict superset/subset support. Maybe something like this, which internally just configures the existing contraint class to check for a strict superset / subset.
Assert.That(collB, Is.StrictSupersetOf(collA));
// or
Assert.That(collB, Is.SupersetOf(collA).Strict);
Sorry, I'd missed this:
Another possibility would be a "Has.More.Items.Than", assuming we just want to check the item count. Is there such a constraint?
Has.Count.GreaterThan(n)
may be what you're looking for here. :)
Hi @stevenaw ,
Thanks for your reply.
Has.Count.GreaterThan(n)
would be too easy! ;-)
-
Has.Count
does not work with Arrays. -
Has.Length
does not work with Lists.
We've got LINQ and IEnumerable<T> all over the place in our code, so we need something implementation-independent. (See issue #1668).
Consequently, I thought of something similar to Has.Exactly(N).Items
, but more like Has.More.Items.Than
.
Kind regards, Reureu
A minor note: these days, assuming the array comes typed as IReadOnlyCollection/IReadOnlyList
, you can use Has.Count
.