NUnit: assert that three or more values ​​are the same

I need to argue that the 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));

      

These two methods only let you compare two values ​​(the first two arguments) and the third is the output message.

I know about CollectionAssert

, but I don't want to create IEnumerables

just for this occasion.

Can I compare more than two arguments in NUnit without using collections? Some method that takes params[]

or whatever.

+3


source to share


4 answers


You can make 2 separate statements:

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

      

Or you can 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 can use like this:

[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);
}

      

+2


source


You can use the constraint based constraint syntax :



Assert.That(new [] { person1, person2, person3 }, Is.All.EqualTo(person1));

      

+1


source


    [Test()]
    [TestCase("a","a","a")]
    [TestCase("a", "b", "a")]
    public void  Dummy(string a, string a1, string a2)
    {

        Assert.That(a, Is.EqualTo(a1).And.EqualTo(a2));

    }

      

Gives

    Expected: "b" and "a"
    But was:  "a"

    1 passed, 1 failed, 0 skipped, took 1.09 seconds (NUnit 2.5.5).

      

0


source


Something else to think about. The first rule of unit testing is "one assert per test", this allows you to more quickly identify where the problem is. If you are claiming that all three matches are the same, then if one of them is off, you need to figure out which one.

public void All_Values_Match()
{
     Assert.AreEqual(person1.Name, person2.Name);
     Assert.AreEqual(person1.Name, person3.Name);
}

      

If you did something on the lines instead

 public void First_Second_Values_Match()
 {
      Assert.AreEqual(person1.Name, person2.Name);
 }

 public void First_Third_Values_Match()
 {
      Assert.AreEqual(person1.Name, person3.Name);
 }

      

This gives you much clearer results for your testing.

0


source







All Articles