相似性 - 抛光和包装

时间:2013-05-23 12:42:37

标签: c# unit-testing xunit autofixture semantic-comparison

我正在使用Ploeh.SemanticComparison的{​​{1}}作为有效表达映射过程预期输出的方法(如Mark Seemann's excellent Advanced Unit Testing course on PluralSight中所述)。

我正在测试一些已正确映射的数据,如下所示:

Likeness

但是,我不高兴: -

  1. 我想将名称应用于相似性(即命名我的​​[Theory, AutoData] static void ShouldYieldIdentifierUpdatedEvent( Vendor sut, string name, string version, Guid id ) { var result = sut.SyncProduct( name, version, id ); var expected = new { ProductId = id, Name = name, Version = version }; expected.AsSource().OfLikeness<NewMappingsEvent>() .Without( y => y.ProgrammaticIdentifier) .ShouldEqual(result); } 自定义)
  2. 我已经失去了.Without( y => y.ProgrammaticIdentifier)的对称性(但我肯定需要来自Assert.Equal( expected,actual, comparer)的错误消息)
  3. 是否有更清晰的方式在表达的约束中表达这一点?

1 个答案:

答案 0 :(得分:1)

如果您有一个名为AssertResemblance的Assertion助手类(如[4]),以及范围内的[{1] static助手,您可以这样说:

var expected = new { ProductId = id, Name = name, Version = version };
AssertResemblance.Like( expected, result, WithoutProgrammaticIdentifier );

或者,如果你有像[2]这样的扩展方法,你可以这样做:

AssertResemblance.Like( expected,result,x=>x.WithoutProgrammaticIdentifier());

或者你可以通过在扩展方法方面实现本地静态助手来实现两个世界中最好的(没有第一个片段中的噪声),但命名相似性(通过在扩展方法中具有实际的impl)([ 2])如[3]所述。


[1]

public static Likeness<T, NewMappingsEvent> WithoutProgrammaticIdentifier<T>( Likeness<T, NewMappingsEvent> that )
{
    return that.Without( x => x.ProgrammaticIdentifier );
}

[2]

static class NewMappingsEventResemblances
{
    public static Likeness<T, NewMappingsEvent> WithoutProgrammaticIdentifier<T>( this Likeness<T, NewMappingsEvent> that )
    {
        return that.Without( x => x.ProgrammaticIdentifier );
    }
}

[3]

static Likeness<T, NewMappingsEvent> WithoutProgrammaticIdentifier<T>( Likeness<T, NewMappingsEvent> that )
{
    return that.WithoutProgrammaticIdentifier();
}

[4]

static class AssertResemblance
{
    public static void Like<T, T2>( T expected, T2 actual )
    {
        Like( expected, actual, x => x );
    }

    public static void Like<T, T2>( T expected, T2 actual, Func<Likeness<T, T2>, Likeness<T, T2>> configureLikeness )
    {
        var likeness = expected.AsSource().OfLikeness<T2>();
        configureLikeness( likeness ).ShouldEqual( actual );
    }
}