【发布时间】:2014-01-08 17:45:55
【问题描述】:
在 Fluent Assertions 中,比较具有 DateTime 属性的对象时,有时会在毫秒内出现轻微的不匹配,并且比较失败。我们绕过它的方法是像这样设置比较选项:
actual.ShouldBeEquivalentTo(expected,
options =>
options.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation))
.WhenTypeIs<DateTime>());
有没有办法设置一次并始终应用它,而不是每次调用 ShouldBeEquivalentTo 时都必须指定它?
更新1: 尝试了以下方法,但它似乎不起作用,测试在 1 毫秒的差异上失败。工厂似乎没有调用新的默认值。
using System;
using FluentAssertions;
using FluentAssertions.Equivalency;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
class Test
{
public DateTime TestDateTime { get; set; }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void SettingFluentAssertionDefault()
{
// arrange
var defaultAssertionOptions = EquivalencyAssertionOptions<DateTime>.Default;
EquivalencyAssertionOptions<DateTime>.Default = () =>
{
var config = defaultAssertionOptions();
config.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs<DateTime>();
return config;
};
var testDateTime = DateTime.Now;
var expected = new Test {TestDateTime = testDateTime};
// act
var actual = new Test {TestDateTime = testDateTime.AddMilliseconds(1)};
// assert
actual.ShouldBeEquivalentTo(expected);
}
}
}
【问题讨论】:
-
TestInitialize 本身是否被调用?
-
是的,调用了 TestInitialize。我什至在执行检查之前将代码 sn-p 直接添加到测试中,它似乎没有被命中。用完整的测试单元更新问题。
标签: c# fluent-assertions