7

我试图了解如何使用使用简单类CreateProxy()的两个实例的功能。Likeness<T>()

public class Band
{
    public string Strings { get; set; }
    public string Brass { get; set; }
}

在下面的测试中,我使用了Fixture一个Create<T>具有Band两个字符串属性值的实例。

[Fact]
public void Equality_Behaves_As_Expected()
{
    // arrange
    var fixture = new Fixture();
    fixture.Customize(new AutoMoqCustomization());

    var original = fixture.Create<Band>();
    //   Brass something like --> "Brass65756b89-d9f3-42f8-88fc-ab6de5ae65cd"
    //   Strings something like --> "Strings7439fa1b-014d-4544-8428-baea66858940"

    // act
    var dupe = new Band {Brass = original.Brass, 
                         Strings = original.Strings};
    //   Brass same as original's like --> "Brass65756b89-d9f3-42f8-88fc-ab6de5ae65cd"
    //   Strings same as original's like --> "Strings7439fa1b-014d-4544-8428-baea66858940"

我尝试了许多不同的断言,但问题的关键似乎是该CreateProxy方法没有填充 的属性Band,因此即使我尝试比较Band具有相同属性值的两个实例,该CreateProxy方法中的实例总是有空值。

    // assert
    var likeness = dupe.AsSource().OfLikeness<Band>()
                       .Without(x => x.Brass).CreateProxy();
    //   Brass & String properties are null using dupe as source of likeness (!)

    //var likeness = original.AsSource().OfLikeness<Band>()
    //                       .Without(x => x.Brass).CreateProxy();
    //   Brass & String properties are null using original as source of likeness (!)

    //Assert.True(likeness.Equals(original)); // Fails
    //Assert.True(original.Equals(likeness)); // Fails

    // below are using FluentAssertions assembly
    //likeness.Should().Be(original);           // Fails (null properties)
    //original.Should().Be(likeness);           // Fails (null properties)
    //likeness.ShouldBeEquivalentTo(original);  // Fails (null properties)
    //original.ShouldBeEquivalentTo(likeness);  // Fails (null properties)
}

我一定是做错了什么,但是我已经阅读了我在 Ploeh 博客和 SO 上可以找到的所有内容,并且找不到一个足够简单的示例来与我正在做的事情进行比较。有任何想法吗?

4

1 回答 1

5

如果您在代理实例上分配值(在调用CreateProxy方法之后),则测试通过:

[Fact]
public void Equality_Behaves_As_Expected()
{
    // AutoMoqCustomization is not necessary.
    var original = new Fixture().Create<Band>();

    var likeness = original
        .AsSource()
        .OfLikeness<Band>()
        .Without(x => x.Brass)
        .CreateProxy();

    likeness.Brass = "foo"; // Ignored.
    likeness.Strings = original.Strings;

    Assert.True(likeness.Equals(original));
    likeness.Should().Be(original);
    likeness.ShouldBeEquivalentTo(original);
}

请记住,这会在目标Likeness类型上创建代理,并且只有该类型的实例会覆盖.Equals

由于类型保持不变,以下断言将不会成功:

Assert.True(original.Equals(likeness));
original.Should().Be(likeness);
original.ShouldBeEquivalentTo(likeness);

更新

从 3.0.4 及更高版本开始,这些值会自动复制到代理实例(这意味着,likeness.Strings = original.Strings;将自动发生)。

于 2013-03-18T11:49:36.317 回答