Home > other >  xUnit test fails while comparing Lists
xUnit test fails while comparing Lists

Time:06-30

Here is my unit test and it fails with a message. Kindly help me fix this.

Update Question:

It looks like i am trying to unit test the JsonSerializer.Deserialize method. So is this a legitimate unit test?

Message:

    Expected got to be equal to {
    JsonFromTo.CMSContacts.ContactsFilter
    {
        cms = "asees", 
        groups = {"jio", "jiso"}
    }, 
    JsonFromTo.CMSContacts.ContactsFilter
    {
        cms = "bsees", 
        groups = {"jto"}
    }
}
, but {
    JsonFromTo.CMSContacts.ContactsFilter
    {
        cms = "asees", 
        groups = {"jio", "jiso"}
    }, 
    JsonFromTo.CMSContacts.ContactsFilter
    {
        cms = "bsees", 
        groups = {"jto"}
    }
}
 differs at index 0.

System Under Test:

public IEnumerable<ContactsFilter> GetFilters(string json)
{
    return JsonSerializer.Deserialize<List<ContactsFilter>>(json);
}

public class ContactsFilter
{
    public string cms { get; set; }
    public List<string> groups { get; set; }
}

Unit Test:

public class CmsContactsTest
{
    public const string Filters = @"[{""cms"": ""asees"",""groups"": [""jio"",""jiso""]},{""cms"": ""bsees"",""groups"": [""jto""]}]";

    [Fact]
    public void Should_Return_List()
    {
        //arrange
        var want = new List<ContactsFilter>()
        {
            new ContactsFilter()
            {
                cms = "asees",
                groups = new List<string>{ "jio", "jiso" }
            },
            new ContactsFilter()
            {
                cms = "bsees",
                groups = new List<string>{ "jto"}
            }
        };

        var got = new CmsContacts().GetFilters(Filters);
        got.Should().Equal(want);
    }
}

CodePudding user response:

You should to use BeEquivalentTo

got.Should().BeEquivalentTo(want);

Quoting BeEquivalentTo source code:

    // Summary:
    //     Asserts that a collection of objects is equivalent to another collection of objects.        
    // ...
    // Remarks:
    //     Objects within the collections are equivalent when both object graphs have equally
    //     named properties with the same value, irrespective of the type of those objects.
    //     Two properties are also equal if one type can be converted to another and the
    //     result is equal. The type of a collection property is ignored as long as the
    //     collection implements System.Collections.Generic.IEnumerable`1 and all items
    //     in the collection are structurally equal. Notice that actual behavior is determined
    //     by the global defaults managed by FluentAssertions.AssertionOptions.

With Equal, elements are compared using their System.Object.Equals(System.Object)

  • Related