我正在为Web API项目做xUnit测试。其中一个方法以毫秒为单位接受UTC日期,我如何测试是否确认API方法的输入参数是有效的毫秒。我有逻辑转换毫秒到日期
public static DateTimeOffset DateTimeCalculation(long milSec)
{
DateTimeOffset epochTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
return epochTime.AddMilliseconds(milSec);
}
测试方法
[Fact]
public async Task GetPersonMethod_MustTake_DateParameter_InMilliSecond()
{
//Arrange
var fixture = new Fixture();
long startDateTimeUtc = 1626994800000;
DateTimeOffset starTimeOffset = DateTimeCalculationHelper.DateTimeCalculation(startDateTimeUtc);
//Act
//Assert
}
在编写单元测试时,您应该清楚地了解实际结果和预期结果。您的测试应该如下所示:
总是问自己,给定一些输入,期望的输出是什么?
public void GetPersonMethod_MustTake_DateParameter_InMilliSecond()
{
//Arrange
long startDateTimeUtc = 1626994800000;
//Act
DateTimeOffset starTimeOffset = DateTimeCalculationHelper.DateTimeCalculation(startDateTimeUtc);
//Assert
string actual = starTimeOffset.ToString();
string expected = "22/07/2021 11:00:00 PM +00:00";
Assert.Equal(expected, actual);
}