3

鉴于这些类:

public class DrumAndBassBand
{
    public Drums Drum { get; set; }
    public Bass Bass { get; set; }
}

public class Instrument
{
    public string Name { get; set; }
    public int SerialNumber { get; set; }
}
public class Drums : Instrument { }
public class Bass : Instrument { }

为什么这个测试通过...

[Fact]
public void DrumAndBassBand_Equality_Behaves_As_Expected_Version_One()
{
    // arrange
    var template = new Fixture().Create<DrumAndBassBand>();

    // act
    var createdBand = new DrumAndBassBand {Drum = template.Drum, Bass = template.Bass};

    // assert         
    var createdLikeness = createdBand.AsSource().OfLikeness<DrumAndBassBand>()
        .Without(x => x.Bass)
        .CreateProxy();
    createdLikeness.Drum = createdBand.Drum;

    Assert.True(createdLikeness.Equals(template));

    var templateLikeness = template.AsSource().OfLikeness<DrumAndBassBand>()
        .Without(x => x.Bass)
        .CreateProxy();
    templateLikeness.Drum = template.Drum;

    Assert.True(templateLikeness.Equals(createdBand));
}

……这个失败了?(区别在于DrumAndBaseBand实例化)

[Fact]
public void DrumAndBassBand_Equality_Behaves_As_Expected_Version_Two()
{
    // arrange
    var template = new Fixture().Create<DrumAndBassBand>();

    // act
    var createdBand =
        new DrumAndBassBand
        {
            Drum = new Drums { Name = template.Drum.Name, SerialNumber = template.Drum.SerialNumber },
            Bass = new Bass { Name = template.Bass.Name, SerialNumber = template.Bass.SerialNumber }
        };

    // assert
    var createdLikeness = createdBand.AsSource().OfLikeness<DrumAndBassBand>()
        .Without(x => x.Bass)
        .CreateProxy();
    createdLikeness.Drum = createdBand.Drum;

    Assert.True(createdLikeness.Equals(template));

    var templateLikeness = template.AsSource().OfLikeness<DrumAndBassBand>()
        .Without(x => x.Bass)
        .CreateProxy();
    templateLikeness.Drum = template.Drum;

    Assert.True(templateLikeness.Equals(createdBand));
}
4

1 回答 1

3

在第二个测试中,Drum和实例与您尝试比较的模板Bass不同。

您始终可以运行Likeness(无需创建代理)并检查输出:

Test 'DrumAndBassBand_Equality_Behaves_As_Expected_Version_Two' failed: 

Ploeh.SemanticComparison.LikenessException:
    The provided value DrumAndBassBand did not match the expected value DrumAndBassBand. 

The following members did not match: 
- Drum.

这基本上意味着您必须在创建实例Likeness比较时提供提示。Drum

测试的前半部分变为:

var createdLikeness = createdBand
    .AsSource().OfLikeness<DrumAndBassBand>()
    .With(x => x.Drum)
        .EqualsWhen((s, d) => s.Drum == createdBand.Drum)
    .Without(x => x.Bass)
    .CreateProxy();

当源目标实际上是createdBand实例时,它Drums等于otherDrumsDrum

同样,测试的后半部分变为:

var templateLikeness = template
    .AsSource().OfLikeness<DrumAndBassBand>()
    .With(x => x.Drum)
        .EqualsWhen((s, d) => s.Drum == template.Drum)
    .Without(x => x.Bass)
    .CreateProxy();

以上允许您进行非常灵活的比较(并且您始终可以进一步自定义它)。

于 2013-03-25T10:15:09.407 回答