1

In C#'s NUnit framework there is Is.EquivalentTo constraint which can be very useful for asserting that two arrays are equivalent in the "permutation" way, (i.e. order of the elements does not matter, only the content.)

E.g. the following test will pass

        [Test]
        public void Test()
        {
            Assert.That(new[] { 1, 2, 3 }, Is.EquivalentTo(new[] { 2, 3, 1 }));
        }

I have been thinking, is there any way to apply the same constraints for jagged arrays? I would like to do the following

        [Test]
        public void Test2D()
        {
            // expected true, but fails
            Assert.That(new[] { new[] { 1 }, new[] { 2, 3 } }, Is.EquivalentTo(new[] { new[] { 3, 2 }, new[] { 1 } }));
        }
andywiecko
  • 306
  • 3
  • 16
  • 3
    Those are not two dimensional arrays, those are [jagged ones](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays) – Guru Stron Jun 04 '21 at 12:03
  • Take a look at [this](https://stackoverflow.com/q/13188088/10713658) and [this](https://stackoverflow.com/q/2893297/10713658). – Mariano Luis Villa Jun 04 '21 at 12:10
  • @MarianoLuisVilla These threads do not resolve my issue. Could you clarify it? – andywiecko Jun 04 '21 at 12:19
  • Apologies, my point was to iterate and compare. I don't know how much of a concern is performance, but you could (pseudocode): `Assert.That(A2.Any(x => x.Sorted() == eachArrayInA1.Sorted())`. – Mariano Luis Villa Jun 04 '21 at 12:49

2 Answers2

1

Your example won't work because of the definition of equivalence in NUnit.

NUnit takes two enumerables (in this case the outer arrays) and checks that the contents are equal without respect to order.

So this will pass:

Assert.That(new[] { new[] { 1 }, new[] { 2, 3 } },
    Is.EquivalentTo(new[] { new[] { 2, 3 }, new[] { 1 } }));

Your example OTOH fails because you want equivalence to apply to the individual items in the collection as well as the collection itself.

As has been pointed out, you could define your own equality comparer and apply it with the .Using() modifier. That's what I would do in this case.

Charlie
  • 12,928
  • 1
  • 27
  • 31
  • Thanks, I guess for my purpose I will sort the inner arrays using LINQ and then use the standard `Is.EquivalentTo()`, best. – andywiecko Jun 04 '21 at 15:34
0

Thanks for the all contributions.

I would like to present my approach for the problem. I simply sort the inner arrays, and then use Is.EquivalentTo()

        [Test]
        public void Test2D()
        {
            var actual = new[] { new[] { 1 }, new[] { 2, 3 } }
                .Select(x => x.OrderBy(e => e));

            var expected = new[] { new[] { 3, 2 }, new[] { 1 } }
                .Select(x => x.OrderBy(e => e));

            Assert.That(actual, Is.EquivalentTo(expected));
        }
andywiecko
  • 306
  • 3
  • 16