Fluent断言:在DateTime属性的集合上使用BeCloseTo

And*_*rke 8 nunit unit-testing fluent-assertions

我正在处理许多项目,每个项目都包含一个DateProcessed属性(可以为空的DateTime),并希望Assert将该属性设置为当前日期.当它完成处理程序时,日期都略有不同.

我想测试所有DateProcessed属性具有相对性(100ms)最近的DateTime.

Fluent Assertions具有.BeCloseTo方法,适用于单个项目.但我想将它用于整个系列.但是在查看集合时,它不能通过Contains()获得.

一个简化的例子......

[TestFixture]
public class when_I_process_the_items
{
    [SetUp]
    public void context()
    {
        items = new List<DateTime?>(new [] { (DateTime?)DateTime.Now, DateTime.Now, DateTime.Now } );
    }

    public List<DateTime?> items;

    [Test]
    public void then_first_item_must_be_set_to_the_current_time()
    {
        items.First().Should().BeCloseTo(DateTime.Now, precision: 100);
    }

    [Test]
    public void then_all_items_must_be_set_to_the_current_time()
    {
        items.Should().Contain .... //Not sure? :(
    }

}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ton 12

您可以通过配置选项在3.5中执行此操作ShouldBeEquivalentTo.例如:

result.ShouldBeEquivalentTo(expected, options =>
{
    options.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs<DateTime>();
    return options;
});
Run Code Online (Sandbox Code Playgroud)

或者说:

result.ShouldBeEquivalentTo(expected, options => options.Using<DateTimeOffset>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs<DateTimeOffset>());
Run Code Online (Sandbox Code Playgroud)

如果要全局设置,请在测试框架的fixture设置方法中实现以下内容:

AssertionOptions.AssertEquivalencyUsing(options =>
{
    options.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs<DateTime>();
    options.Using<DateTimeOffset>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs<DateTimeOffset>();
    return options;
});
Run Code Online (Sandbox Code Playgroud)


Den*_*men 4

作为对你的问题的直接回答,你可以做类似的事情items.Should().OnlyContain(i => (i - DateTime.Now) < TimeSpan.FromMilliseconds(100))。

然而,依赖的单元测试DateTime.Now是一种非常糟糕的做法。你能做的就是引入这样的东西:

public static class SystemContext
{
    [ThreadStatic]
    private static Func<DateTime> now;

    public static Func<DateTime> Now
    {
        get { return now ?? (now = () => DateTime.Now); }
        set { now = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后不要引用DateTime.Now,而是使用SystemContext.Now()来获取当前时间。如果这样做,您可以为特定单元测试“设置”当前时间,如下所示:

SystemContext.Now = () => 31.March(2013).At(7, 0);
Run Code Online (Sandbox Code Playgroud)