c# - 处理 2 月 28 日的 DateTimeOffset

标签 c# unit-testing date

我今天(5 月 29 日)有一个测试失败了。这是一个非常简单的测试,可验证过去 3 个月内购买的商品,其大致思路是...

var purchaseDate = DateTimeOffset.Now.AddMonths(-3); // returns the 28th of February
Assert.True(purchaseDate.AddMonths(3).Date >= DateTimeOffset.Now.Date) // 28th of February + 3 months is the 28th of May

此测试仅在今天失败。

我假设这个问题以前已经遇到过很多次了,那么,有没有办法在 5 月 29 日不切换逻辑的情况下处理它?<​​/p>

最佳答案

我认为你的问题更多的是设计错误。我会将当前日期作为可选依赖项注入(inject),以确保我可以使用我想要的任何值进行测试。

让我们以您可能拥有的这项小型服务为例:
(使用任何你喜欢的DI)

public class MyService {

    // Private variables that will be initialized by constructor

    private readonly DateTimeOffset now;

    public MyService(MyFirstDependency dependency, DateTimeOffset now = DateTimeOffset.Now) {
         // Assign here your private variables
         this.now = now;
    }


    public void ValidateDateIsNotBefore3MonthsAgo(DateTimeOffset myDateToValidate) {
        if (!myDateToValidate.AddMonths(3).Date >= now.Date) {
             throw new WhateverYouWantException("Date is before 3 months ago");
        }
    }

}

这样,当您实例化测试时,您可以传递带有您选择的值的 DateTimeOffset。您不再依赖当前日期。

编辑:我忘了你还可以使用Fakes无需修改代码即可模拟当前日期,但它是 not available for every version of Visual Studio

关于c# - 处理 2 月 28 日的 DateTimeOffset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50574675/

相关文章:

c# - Sitecore:在内容编辑器中隐藏字段?

unit-testing - NestJS 模拟返回 Guard 的 Mixin

php 程序找到我的生日,其中日期名称 "Monday"再过 100 年

c# - 使用 Excel 文件检索数据以进行单元测试 C#

对于公共(public)方法,Python 模拟补丁无法按预期工作

java - 安卓/Java : Annual countodwn with having to update it constantly

javascript - js :using dateformat with google geochart(getformattedValue)?

c# - WPF:带有图标 View 的 ListView?

c# - UIPATH - 未知类型

c# - 编译错误集合被修改