1

我使用Ploeh.SemanticComparison'sLikeness作为一种有效表达映射过程预期输出的方式(如Mark Seemann 在 PluralSight 上的优秀高级单元测试课程中所述)。

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

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

但是,我不高兴:-

  1. 我想为 Resemblance 应用一个名称(即命名我的.Without( y => y.ProgrammaticIdentifier)​​自定义)
  2. 我已经失去了对称性Assert.Equal( expected,actual, comparer)(但我肯定需要来自 的错误消息ShouldEqual

有没有更简洁的方式在表达的约束范围内表达这一点?

4

1 回答 1

1

如果你有一个 Assertion 助手类AssertResemblance(如 [4]),并且static在范围内有一个如 [1] 的助手,你可以这样说:

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

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

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

或者,您可以两全其美(没有第一个片段中的噪音),但通过根据扩展方法([2])实现本地静态帮助器来命名相似度(通过在扩展方法中具有实际的 impl)如[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 );
    }
}
于 2013-05-23T12:56:49.980 回答