Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 2月28日处理DateTimeOffset_C#_Unit Testing_Date - Fatal编程技术网

C# 2月28日处理DateTimeOffset

C# 2月28日处理DateTimeOffset,c#,unit-testing,date,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 2

我今天(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日不切换逻辑的情况下处理它?

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

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

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


编辑:我忘了你也可以使用模拟当前日期而不必修改代码,但它也会在7月31日失败。除了以天计算而不是以月计算之外,我不知道你还能做什么。你很幸运,我们没有使用犹太人的日历-那里的月计算更糟糕。“因此,在非闰年出生在阿达尔的人将在闰年在阿达尔二世庆祝他的生日。然而,在闰年的任何一个阿达尔出生的人将在非闰年的阿达尔庆祝他的生日,但在非闰年的阿达尔一世30岁出生的人将在尼桑一世庆祝他的生日,因为阿达尔在n在编写单元测试时,人们往往会忽略这一点:当前日期/时间是一个外部依赖项。
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");
        }
    }

}