【问题标题】:FluentAssertions: How to compare properties of a different nameFluentAssertions:如何比较不同名称的属性
【发布时间】:2016-10-02 18:16:41
【问题描述】:

我有两个相同类型的对象需要比较,但是 objectA 上一个对象属性的值应该等于 objectB 上另一个名称的属性。

鉴于我的对象:

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

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

我需要验证actual.Alpha == expected.Alpha 和actual.Beta == expected.Alpha

这个可以吗?

【问题讨论】:

    标签: c# unit-testing vs-unit-testing-framework fluent-assertions


    【解决方案1】:

    我想你想要类似的东西:

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

    另外,如果你想比较对象列表

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

    【讨论】:

    • 感谢您的回复。这也可以应用于集合对象吗?假设我有 List 预期; List 实际;实际.ShouldBeEquivalentTo(预期);
    • 我认为fluent assertion 不支持这种比较。我知道如何在 NUnit 中进行操作,以及如何创建一种在 vs-unit-testing-framework 中使用它的方法。我将编辑我的 awnser 并编写方法
    猜你喜欢
    • 2021-12-18
    • 2020-01-20
    • 1970-01-01
    • 2013-06-08
    • 2014-11-12
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多