如何在 FluentAssertions 中为平等使用特定的比较器函数
How to use a specific comparer func for Equality in FluentAssertions
我正在编写一个 Akka.NET Testkit 实现,它在后台使用 FluentAssertions,但无法弄清楚如何编写 'last' 断言:使用自定义 Func 相等比较器的相等性(虽然当然,收到一条不错的错误消息)。
public void AssertEqual<T>(T expected, T actual,
Func<T, T, bool> comparer,
string format = "", params object[] args)
{
// This works, but does not give a good message:
comparer(expected, actual).Should().BeTrue(format, args);
// But this doesn't work at all:
// actual.Should().BeEquivalentTo(expected, options =>
options.Using<T>( x => comparer(x.Subject, expected).Should().BeTrue())
.WhenTypeIs<T>(),
format, args);
}
我很确定 FA 中一定有一些奇特的方法可以做到这一点,但我找不到它。
为什么不将对 BeEquivalentTo
的调用替换为构建在 Execute.Assertion
之上的自定义断言,如 extensibility section 中所述?
或者直接使用 BeEquivalentTo
选项?您甚至可以像这样将其包装在自己的代码中:
public static void AssertEqual<T>(T actual, T expected,
Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config)
{
Func<EquivalencyAssertionOptions<TEvent>, EquivalencyAssertionOptions<TEvent>> effectiveConfig = opt =>
{
// customize the assertion in addition to the caller's customization
return config(opt);
};
actual.Should().BeEquivalentTo(expected, effectiveConfig);
}
我正在编写一个 Akka.NET Testkit 实现,它在后台使用 FluentAssertions,但无法弄清楚如何编写 'last' 断言:使用自定义 Func 相等比较器的相等性(虽然当然,收到一条不错的错误消息)。
public void AssertEqual<T>(T expected, T actual,
Func<T, T, bool> comparer,
string format = "", params object[] args)
{
// This works, but does not give a good message:
comparer(expected, actual).Should().BeTrue(format, args);
// But this doesn't work at all:
// actual.Should().BeEquivalentTo(expected, options =>
options.Using<T>( x => comparer(x.Subject, expected).Should().BeTrue())
.WhenTypeIs<T>(),
format, args);
}
我很确定 FA 中一定有一些奇特的方法可以做到这一点,但我找不到它。
为什么不将对 BeEquivalentTo
的调用替换为构建在 Execute.Assertion
之上的自定义断言,如 extensibility section 中所述?
或者直接使用 BeEquivalentTo
选项?您甚至可以像这样将其包装在自己的代码中:
public static void AssertEqual<T>(T actual, T expected,
Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config)
{
Func<EquivalencyAssertionOptions<TEvent>, EquivalencyAssertionOptions<TEvent>> effectiveConfig = opt =>
{
// customize the assertion in addition to the caller's customization
return config(opt);
};
actual.Should().BeEquivalentTo(expected, effectiveConfig);
}