.Net单元测试UTC和当地时差

时间:2015-03-19 10:54:26

标签: .net unit-testing datetime utc

我正在尝试对以下方法进行单元测试:

Public Shared Function GetLocalTimeWithTimeDifferenceUTC(startTime As DateTime) As String
    Dim localTime As String = ""
    Dim timeUTC As DateTime = startTime.ToUniversalTime()
    Dim timeDiff As TimeSpan = startTime.Subtract(timeUTC)
    Dim sSign As String = "+"
    If timeDiff.TotalMinutes < 0 Then
        sSign = "-"
        timeDiff = timeDiff.Negate
    End If
    Dim offsetUTC As String = sSign & String.Format("{0:d2}:{1:d2}", timeDiff.Hours, timeDiff.Minutes)
    localTime = startTime.ToString("yyyy-MM-ddTHH:mm:ss") & offsetUTC

    Return localTime
End Function

它返回(例如startTime = 2015,3,18,10,0,0时差加两小时)2015-03-18T10:00:00 + 02:00。

这是我的单元测试:

Public Sub GetLocalTimeWithTimeDifferenceUTC_Test()
        Dim expected As String
        Dim actual As String
        Dim param As New System.DateTime(2015, 3, 5, 10, 0, 0)
        expected = "2015-03-05T10:00:00+03:00"
        Using (ShimsContext.Create())
            System.Fakes.ShimDateTime.NowGet = Function() As System.DateTime
                                                   Return New DateTime(2015, 3, 5, 10, 0, 0)
                                               End Function
            System.Fakes.ShimDateTime.UtcNowGet = Function() As System.DateTime
                                                      Return New DateTime(2015, 3, 5, 7, 0, 0)
                                                  End Function
            actual = StringFunctions.GetLocalTimeWithTimeDifferenceUTC(param)
        End Using
        Assert.AreEqual(expected, actual)
    End Sub

我应用于DateTime.Now和DateTime.UtcNow的更改不起作用,测试失败。当我尝试使用真正的本地时间时,它可以工作。是否可能由ToUniversalTime()函数引起?我应该改变一些方法吗?任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:-1)

你必须像这样提供本地和UTC DateTimeKind

Public Sub GetLocalTimeWithTimeDifferenceUTC_Test()
    Dim expected As String
    Dim actual As String
    Dim param As New System.DateTime(2015, 3, 5, 10, 0, 0)
    expected = "2015-03-05T10:00:00+03:00"
    Using (ShimsContext.Create())
        System.Fakes.ShimDateTime.NowGet = Function() As System.DateTime
                                               Return New DateTime(2015, 3, 5, 10, 0, 0, DateTimeKind.Local)
                                           End Function
        System.Fakes.ShimDateTime.UtcNowGet = Function() As System.DateTime
                                                  Return New DateTime(2015, 3, 5, 7, 0, 0, DateTimeKind.Utc)
                                              End Function
        actual = StringFunctions.GetLocalStartTime(param)
    End Using
    Assert.AreEqual(expected, actual)
End Sub