当主题是DateTime时,ShouldBeEquivalentTo对等效对象失败

时间:2013-11-28 04:41:27

标签: .net datetime nodatime fluent-assertions

我正在尝试做什么

我刚刚设置了一个测试,以确保将NodaTime LocalDateTime映射到.NET DateTime,并保留相同的日期和时间值。我正在使用FluentAssertions的ShouldBeEquivalentTo方法来比较相应的属性值。

[TestClass]
public class LocalDateTimeMapping
{
    [TestMethod]
    public void RetainsComponentValues()
    {
        var nodatimeTime = new LocalDateTime();
        var dotnetTime = nodatimeTime.ToDateTimeUnspecified();

        dotnetTime.ShouldBeEquivalentTo(nodatimeTime,
            o => o
                .Including(d => d.Year)
                .Including(d => d.Month)
                .Including(d => d.Day)
                .Including(d => d.Hour)
                .Including(d => d.Minute)
                .Including(d => d.Second)
                .Including(d => d.Millisecond)
        );
    }
}

问题

测试失败:

Expected subject to be 01/01/1970 00:00:00, but found <1970-01-01>.

With configuration:
- Select property System.DateTime.Year
- Select property System.DateTime.Month
- Select property System.DateTime.Day
- Select property System.DateTime.Hour
- Select property System.DateTime.Minute
- Select property System.DateTime.Second
- Select property System.DateTime.Millisecond
- Match property by name (or throw)
- Invoke Action<DateTime> when info.RuntimeType.IsSameOrInherits(System.DateTime)
- Invoke Action<String> when info.RuntimeType.IsSameOrInherits(System.String)

我不知道最后两行是什么意思。

我尝试了什么

  1. 在调试器中运行测试以确认每个测试的值都相同。
  2. 通过删除不同属性的Include来查看问题是否属于特定属性。
  3. 基于EquivalencyAssertionOptions<DateTime>.Empty()的配置,以确保不会隐含涉及额外的检查或属性。
  4. 将所有内容简化为以下内容。

    dotnetTime.ShouldBeEquivalentTo(nodatimeTime,
        o => EquivalencyAssertionOptions<DateTime>.Empty()
    );
    

2 个答案:

答案 0 :(得分:2)

错误消息中的以下行表明正在对DateTime进行某种特殊处理:

Invoke Action<DateTime> when info.RuntimeType.IsSameOrInherits(System.DateTime)

我尝试交换我比较的两个日期时间,这解决了问题:

nodatimeTime.ShouldBeEquivalentTo(dotnetTime,
    o => o
        .Including(d => d.Year)
        .Including(d => d.Month)
        .Including(d => d.Day)
        .Including(d => d.Hour)
        .Including(d => d.Minute)
        .Including(d => d.Second)
        .Including(d => d.Millisecond)
);

所以我得出结论,不应该在.NET ShouldBeEquivalentTo上调用DateTime

答案 1 :(得分:1)

你可以将日期时间与流畅的断言进行比较,他们已经添加了很多很好的方法来链接它:

https://fluentassertions.com/documentation/

e.g。

theDatetime.Should().BeLessThan(10.Minutes()).Before(otherDatetime);