Search code examples
c#unit-testingassertfluent-assertions

C# Testing - compare list of custom type


I'm trying to write test checking if JSON converter corectly deserialize input to my custom list

    [TestMethod]
    public void JSONInput_Changed()
    {
        List<PointOnChart> _expectedPointsOnChart;
        _expectedPointsOnChart = new List<PointOnChart>();
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:00:00.000Z", Value1 = 10, Value2 = 20, Value3 = 30 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:01:00.000Z", Value1 = 11, Value2 = 21, Value3 = 31 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:02:00.000Z", Value1 = 12, Value2 = 22, Value3 = 32 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:03:00.000Z", Value1 = 13, Value2 = 23, Value3 = 33 });

        MultipleBarChart multipleBarChartTest = new MultipleBarChart();
        multipleBarChartTest.MeInitialize(DateTimeIntervalType.Minutes);
        string JSONstring = System.IO.File.ReadAllText(@"C:\Users\slawomirk\source\repos\VIXCharts\iFixMultipleBarChartTests\TestJson.txt");
        multipleBarChartTest.JSONInput = JSONstring;
        List<PointOnChart> resultPointsOnChart = multipleBarChartTest.PointsOnChart;

        //bool areEqual = _expectedPointsOnChart.SequenceEqual(resultPointsOnChart);
        IEnumerable<PointOnChart> resultList;
        resultList = _expectedPointsOnChart.Except(resultPointsOnChart);
        if (resultList.Any())
        {
            Assert.Fail();
        }
    }

List contains object of this class

public class PointOnChart
{
    public string Timestamp { get; set; }
    public double Value1 { get; set; }
    public double Value2 { get; set; }
    public double Value3 { get; set; }
}

And this is file I'm reading to deserialize:

[{"Timestamp":"2020-02-14T09:00:00.000Z","Value1":10,"Value2":20,"Value3":30}, {"Timestamp":"2020-02-14T09:01:00.000Z","Value1":11,"Value2":21,"Value3":31}, {"Timestamp":"2020-02-14T09:02:00.000Z","Value1":12,"Value2":22,"Value3":32}, {"Timestamp":"2020-02-14T09:03:00.000Z","Value1":13,"Value2":23,"Value3":33}]

I tried numerous ways to compare two Lists but all of them fails eg.: - Fluent Assertion - CollectionAssert

When I inspect both List in debug they are identical. I know it's probably trivial but I could find any solution online, thanks in advance.


Solution

  • You should implement the Equals method for the PointOnChart class, something like this:

    public override bool Equals(object other)
    {
        if (object.ReferenceEquals(other, this)) return true;
    
        var obj = other as PointOnChart;
    
        if (obj == null) return false;
    
        return this.Timestamp == obj.Timestamp && this.Value1 == obj.Value1 && this.Value2 == obj.Value2 && this.Value3 == obj.Value3;
    }
    

    This way the SequenceEquals extension method will operate properly.