如何在C#中使用严格的类型相等性声明结构对象对等物

时间:2018-10-23 19:16:18

标签: c# unit-testing fluent-assertions

您如何优雅地断言两个.NET对象之间的以下等效性(最好使用Fluent断言库)?

如果满足以下条件,则两个对象在结构上等效:

  • 两个对象都是相同的(运行时)类型,并且
  • 两个对象的公共属性(递归)结构等效

请注意,subject.Should().BeEquivalentTo(expectation)不起作用,因为BeEquivalentTo不检查类型相等性。例如,如果我们有两个类AB,每个类都有一个属性object X { get; set; },则这两个对象

new A { X = new B { X = new A() }}

new B { X = new A { X = new B() }}

即使它们的类型以及它们的属性和子属性的类型不匹配,也将被BeEquivalentTo视为等效,因此在上述定义上在结构上不是等效的。

2 个答案:

答案 0 :(得分:0)

我想出了这个解决方案,但我希望有一个更优雅的解决方案。

定义自定义import React, { Component } from 'react'; class Main extends Component { constructor(props) { super(props); this.state = { show: false, encryptedValue: null }; } encrypt = () => { let input = document.getElementById("inputText").value; let encryptedValue; let temp = ""; for(let i = 0; i < input.length; i++) { temp += input[i]; switch(input[i].charAt(i)) { case "a": encryptedValue = "x"; break; case "b": encryptedValue = "y"; break; case "c": encryptedValue = "z"; break; default: encryptedValue = null; } } document.getElementById("res").innerHTML = temp; this.setState({show: true, encryptedValue: encryptedValue}); }; render() { return( <div> <input type="text" placeholder="type something" id="inputText"/> <button onClick={() => this.encrypt()}>Click to encrypt</button> <h1 id="res">{this.state.encryptedValue}</h1> </div> ); } } export default Main;

IEquivalencyStep

然后像这样检查等效性:

    public class StrictTypeEquivalence : IEquivalencyStep
    {          
        public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config)
        {
            return context.Subject != null && context.Expectation != null &&
                   context.Subject.GetType() != context.Expectation.GetType();
        }

        public bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
        {
            throw new AssertionFailedException($"{context.SelectedMemberPath}: Expected type {context.Expectation.GetType()} but found {context.Subject.GetType()} instead.");
        }
    }

答案 1 :(得分:-1)

subject.Should().BeOfType(expectation.GetType).And.Should().BeEquivalentTo(expectation);