1

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.

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#) ?

Jon Bates
  • 3,055
  • 2
  • 30
  • 48
M_P
  • 31
  • 2
  • `Assert.AreEqual(List1e.empId,List2e.empId);` this won't compile... Also try to format your code better – Vidmantas Blazevicius Jan 14 '20 at 10:54
  • thanks @VidmantasBlazevicius but i have already tried this but not working. – M_P Jan 14 '20 at 11:07
  • Can you explain what do you want to test? The list has no empId, but items have... what behavior you expect here? That the first list should have a set of items with the empId of second one? – Anton Anpilogov Jan 14 '20 at 11:32
  • @M_P as it is already mentioned you need to to set which one you need to check in the list use sth like this `List1e[0].empId` or elaborate your logic so we can provide more. If you want to know more about object equality you can take a look here -> https://stackoverflow.com/questions/59458136/how-can-i-compare-two-lists-with-xunit-test/59458398#59458398 – panoskarajohn Jan 14 '20 at 12:24

4 Answers4

1

You may have to override the Equals and GetHashCode method in the class EmpInfo and write the compare logic .

Use the above methods to check whether all the objects in one list are present in another .

Test12345
  • 1,625
  • 1
  • 12
  • 21
  • It is also a good idea to inherit from the IEquateable -> https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=netframework-4.8 – panoskarajohn Jan 14 '20 at 12:30
1

Alternatives to checking that the list contains only items with the same ID:

  1. Implement equality for the EmpInfo class, as suggested by User965207, either by overriding Equals or implementing the IEquatable interface. NUnit will use either one if present. 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. 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. This approach only requires changing the test code.

  3. Use NUnit's List class to do essentially the same as option 2 for you...

    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. 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.

Charlie
  • 12,928
  • 1
  • 27
  • 31
1

There are numerous ways to achieve it

  1. Use https://fluentassertions.com/objectgraphs/ (The easiest and fastest way)
    List1e.Should().BeEquivalentTo(List2e);
  1. Move all the individual comparisons to the .Equals method (Or implement 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
    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)
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

How about Assert.IsTrue(List1e.SequenceEqual(List2e))

Sean
  • 75
  • 2
  • 9
  • don't want to check sequence i want to check one particular item. – M_P Jan 14 '20 at 11:08
  • Ah, ok. Then you would want `Assert.IsTrue(List1e.Select(x => x.empId).SequenceEqual(List2e.Select(x => x.empId))` So, quick explanation - `Select` creates a list of the `empId`s for each object. So we create a list of the `empIds` for each list, and then compare those lists with `SequenceEqual`. – Sean Jan 14 '20 at 11:11