C# Fluent Assertions global options for ShouldBeEquivalentTo

前端 未结 3 1795
我在风中等你
我在风中等你 2021-02-19 03:41

In Fluent Assertions when comparing objects with DateTime properties there are sometimes a slight mismatch in the milliseconds and the comparison fail. The way we get around it

相关标签:
3条回答
  • 2021-02-19 04:04

    I am afraid the closest thing you can come to, is providing new methods

    public static void ShouldBeEquivalentToDef<T>(this T subject, object expectation, string reason = "",
        params object[] reasonArgs)
    {
        ShouldBeEquivalentToDef(subject, expectation, config => config, reason, reasonArgs);
    }
    
    public static void ShouldBeEquivalentToDef<T>(this T subject, object expectation,
        Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config, string reason = "", params object[] reasonArgs)
    {
        var context = new EquivalencyValidationContext
        {
            Subject = subject,
            Expectation = expectation,
            CompileTimeType = typeof (T),
            Reason = reason,
            ReasonArgs = reasonArgs
        };
    
        var defConstructedOptions = config(EquivalencyAssertionOptions<T>.Default());
        defConstructedOptions.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation))
                .WhenTypeIs<DateTime>()
    
        new EquivalencyValidator(defConstructedOptions).AssertEquality(context);
    }
    
    0 讨论(0)
  • 2021-02-19 04:14

    Actually, you can. The default configuration factory is exposed by the static property EquivalencyAssertionOptions<Test>.Default. You can easily assign an alternative configuration for a particular data type, or extend the default configuration with additional behavior. Something like:

    var defaultAssertionOptions = EquivalencyAssertionOptions<Test>.Default;
    
    EquivalencyAssertionOptions<Test>.Default = () =>
    {
        var config = defaultAssertionOptions();
        config.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs<DateTime>();
        return config;
    };
    

    If you want you can get the current default and tuck that away in some variable that you use from your factory method.

    0 讨论(0)
  • 2021-02-19 04:16

    Now this can be done with the AssertionOptions static class. To use a simple example:

    [TestInitialize]
    public void TestInit() {
      AssertionOptions.AssertEquivalencyUsing(options => options.ExcludingMissingMembers());
    }
    

    Or as in the example above:

    AssertionOptions.AssertEquivalencyUsing(options =>
      options.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs<DateTime>()
    );
    
    0 讨论(0)
提交回复
热议问题