1

I have two objects of the same type that I need to compare, but the value of one object property on objectA should be equal to a property of a different name on objectB.

Given my object:

class MyObject
{
    public string Alpha {get; set;}
    public string Beta {get; set;}
}

var expected = new MyObject {"string1", "string1"};
var actual = new MyObject {"string1", null};

I need to verify that actual.Alpha == expected.Alpha and actual.Beta == expected.Alpha

Can this be done?

Chris
  • 11
  • 1
  • 2

1 Answers1

1

I think you want something like it:

// VS Unit Testing Framework
Assert.IsTrue(actual.Alpha == expected.Alpha, "the Alpha objects are not equals");
Assert.IsTrue(actual.Beta == expected.Beta, "the Beta objects are not equals");

// Fluent Assertion
actual.Alpha.Should().Be(expected.Alpha);
actual.Beta.Should().Be(expected.Beta);

Also, if you want to compare lists of objects

// Helper method to compare - VS Unit Testing Framework
private static void CompareIEnumerable<T>(IEnumerable<T> one, IEnumerable<T> two, Func<T, T, bool> comparisonFunction)
{
    var oneArray = one as T[] ?? one.ToArray();
    var twoArray = two as T[] ?? two.ToArray();

    if (oneArray.Length != twoArray.Length)
    {
        Assert.Fail("Collections have not same length");
    }

    for (int i = 0; i < oneArray.Length; i++)
    {
        var isEqual = comparisonFunction(oneArray[i], twoArray[i]);
        Assert.IsTrue(isEqual);
    }
}

public void HowToCall()
{
    // How you need to call the comparer helper:
    CompareIEnumerable(actual, expected, (x, y) => 
        x.Alpha == y.Alpha && 
        x.Beta == y.Beta );
}
Striter Alfa
  • 1,577
  • 1
  • 14
  • 31
  • Thank you for the response. Can this also be applied to collection objects? Say I have List expected; List actual; actual.ShouldBeEquivalentTo(expected); – Chris Jun 03 '16 at 17:25
  • I think fluent assertion does not support this kind of comparison. I know how to do in NUnit and how to create an method to use it in vs-unit-testing-framework. I will edit my awnser and write the method – Striter Alfa Jun 03 '16 at 17:58