简体   繁体   English

Nunit断言的条件

[英]Condition if for Nunit assert

I need to compare two List s by NUnit's Assert.AreEqual . 我需要通过NUnit的Assert.AreEqual比较两个List If this statement is false (lists not the same) - then I need find elements in lists which not the same. 如果此语句为假(列表不相同)-那么我需要在列表中查找不相同的元素。

How I can use If statement for know- Assert return true or false ? 如何使用If语句获取知识-声明返回truefalse

It seems that nunit CollectionAssert.AreEquivalent is exactly what you were looking for. 看起来nunit CollectionAssert.AreEquivalent正是您要寻找的。

This method compare between the collections. 此方法在集合之间进行比较。 If a mismatch was found then the method will throw exception with the difference. 如果发现不匹配,则该方法将抛出具有差异的异常。

Here's a possible solution. 这是一个可能的解决方案。

    [Test]
    public void TestMethod1()
    {
        List<int> a = new List<int>();
        List<int> b = new List<int>();

        //Fake data              
        a.Add(1);
        b.Add(2);
        b.Add(2);

        Assert.IsTrue(AreEquals(a,b), GetDifferentElements(a,b));
    }

    private string GetDifferentElements(List<int> a, List<int> b)
    {

        if (AreEquals(a, b))
        {
            return string.Empty;
        }
        if (a.Count != b.Count)
        {
            return "The two lists have a different length";
        }
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < a.Count; i++)
        {
            if (a[i] != b[i])
            {
                s.Append(i.ToString() + " ");
            }
        }
        return string.Format("Elements at indexes {0} are different", s.ToString());
    }

    private bool AreEquals(List<int> a, List<int> b)
    {
        if (a.Count != b.Count)
        {
            return false;
        }
        for (int i = 0; i < a.Count; i++)
        {
            if (a[i] != b[i])
            {
                return false;
            }
        }
        return true;
    }

UPDATE UPDATE

Of course I was unaware of the CollectionAssert.AreEquivalent method provided in the accepted answer. 当然,我不知道所接受答案中提供的CollectionAssert.AreEquivalent方法。 That's a better solution of course! 当然,这是一个更好的解决方案!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM