简体   繁体   English

如何在 Nunit 中使用 Assert 检查两个列表项的相等性

[英]How to check equality of items of two list using Assert in Nunit

I'm fairly new to unit testing.我对单元测试相当陌生。 The following code is just for reference.以下代码仅供参考。 I want to check empId of list one is same as the emp id of list 2 or not.我想检查列表 1 的 empId 是否与列表 2 的 emp id 相同。

public class EmpInfo
{    
    public EmpInfo( string lastName,string firstName, string empId)
    {
        EAlphabeticLastName = lastName;
        EFirstName = firstName;
        EmpId = empId;
    }
}

[Test]
[Category("Explicit")]
public void testEmp() 
{
    public List<EmpInfo> List1e = new List<EmpInfo>(){        
            new EmpInfo("dx","Tex","25")  
    };

    public List<EmpInfo> List2e = new List<EmpInfo>(){          
            new EmpInfo("dx","Tex","25")  
    };
    Assert.AreEqual(List1e.empId,List2e.empId);
}

What is the correct way to check equality of list items in Nunit (C#) ?在 Nunit (C#) 中检查列表项是否相等的正确方法是什么?

You may have to override the Equals and GetHashCode method in the class EmpInfo and write the compare logic .您可能必须覆盖EmpInfo类中的EqualsGetHashCode方法并编写比较逻辑。

Use the above methods to check whether all the objects in one list are present in another .使用上述方法检查一个列表中的所有对象是否都存在于另一个列表中。

Assert.IsTrue(List1e.SequenceEqual(List2e))怎么样?

Alternatives to checking that the list contains only items with the same ID:检查列表是否仅包含具有相同 ID 的项目的替代方法:

  1. Implement equality for the EmpInfo class, as suggested by User965207, either by overriding Equals or implementing the IEquatable interface.按照EmpInfo建议,通过覆盖Equals或实现IEquatable接口来实现EmpInfo类的IEquatable NUnit will use either one if present.如果存在,NUnit 将使用其中之一。 If you don't have control over the code of the system under test, this is of course not available to you.如果您无法控制被测系统的代码,这当然对您不可用。

  2. Use a Select statement to create a new list for comparison, as suggested by Sean.按照 Sean 的建议,使用Select语句创建一个新列表进行比较。 You actually only need to do this for the actual value being tested.您实际上只需要为正在测试的实际值执行此操作。 Your expected value can just be a list or array of empids in the first place.首先,您的预期值可以只是一个 empids 列表或数组。 This approach only requires changing the test code.这种方法只需要更改测试代码。

  3. Use NUnit's List class to do essentially the same as option 2 for you...使用 NUnit 的List类为您执行与选项 2 基本相同的操作...

    Assert.That(List.Map(List1e).Property("empid"), Is.EqualTo(new [] {"empid1", "empid2" / etc /})); Assert.That(List.Map(List1e).Property("empid"), Is.EqualTo(new [] {"empid1", "empid2" / etc /}));

    Since you have not provided a full implementation of EmpInfo , I made the assumption that empid is a property.由于您尚未提供EmpInfo的完整实现, EmpInfo我假设empid是一个属性。 If it's a field, this won't work.如果它是一个字段,这将不起作用。

I realize I haven't added a lot to the prior answers here, but I thought a summary of the possible approaches with pros and cons would be of help.我意识到我没有在这里对先前的答案添加很多内容,但我认为总结可能的利弊方法会有所帮助。

There are numerous ways to achieve it有很多方法可以实现

  1. Use https://fluentassertions.com/objectgraphs/ (The easiest and fastest way)使用https://fluentassertions.com/objectgraphs/ (最简单快捷的方式)
    List1e.Should().BeEquivalentTo(List2e);
  1. Move all the individual comparisons to the .Equals method (Or implement IEqualityComparer )将所有单独的比较移动到.Equals方法(或实现IEqualityComparer

  2. Build a helper method that iterates through public properties by reflection and assert each property构建一个辅助方法,通过反射遍历公共属性并断言每个属性

      public static void PropertyValuesAreEquals(object actual, object expected)   {
        PropertyInfo[] properties = expected.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            object expectedValue = property.GetValue(expected, null);
            object actualValue = property.GetValue(actual, null);
          if (!Equals(expectedValue, actualValue))
                Assert.Fail("Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue);
          //……………………………….
        }

  1. Use JSON to compare the object's data使用 JSON 比较对象的数据
    public static void AreEqualByJson(object expected, object actual)
    {
       var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
       var expectedJson = serializer.Serialize(expected);
       var actualJson = serializer.Serialize(actual);
       Assert.AreEqual(expectedJson, actualJson);
    }
  1. Use Property Constraints (NUnit 2.4.2)使用属性约束(NUnit 2.4.2)

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

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