Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit: Assert that three or more values are the same

Tags:

c#

nunit

I need to assert that three values are the same.

For example, I need something like this

Assert.AreEqual(person1.Name, person2.Name, person3.Name);

Assert.That(person1.Name, Is.EqualTo(person2.Name), Is.EqualTo(person3.Name));

Those two methods allow only to compare two values (the first two arguments), and the third argument is the output message.

I know about CollectionAssert but I don't want to create IEnumerables just for this case.

Is it possible to compare more than two arguments in NUnit without using collections ? Some method which accepts params[] or something else.

like image 800
Dimitar Tsonev Avatar asked Oct 28 '25 15:10

Dimitar Tsonev


1 Answers

You can do 2 separate asserts:

Assert.AreEqual(person1.Name, person2.Name);
Assert.AreEqual(person1.Name, person3.Name);

Or you could create a helper function:

public static class AssertEx
{
    public static void AllAreEqual<T>(params T[] items)
    {
        for (int i = 1; i < items.Length; i++)
        {
            Assert.AreEqual(items[0], items[i]);
        }
    }
}

Which you could use like so:

[Test]
public void TestShouldPass()
{
    var person1 = new Person { Name = "John" };
    var person2 = new Person { Name = "John" };
    var person3 = new Person { Name = "John" };

    AssertEx.AllAreEqual(person1.Name, person2.Name, person3.Name);
}

[Test]
public void TestShouldFail()
{
    var person1 = new Person { Name = "John" };
    var person2 = new Person { Name = "Bob" };
    var person3 = new Person { Name = "John" };

    AssertEx.AllAreEqual(person1.Name, person2.Name, person3.Name);
}
like image 141
Trevor Pilley Avatar answered Oct 31 '25 04:10

Trevor Pilley