Chris
Chris

Reputation: 11

FluentAssertions: How to compare properties of a different name

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?

Upvotes: 1

Views: 4271

Answers (1)

Striter Alfa
Striter Alfa

Reputation: 1577

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 );
}

Upvotes: 1

Related Questions