gpt4 book ai didi

c# - 如何对空枚举进行单元测试?

转载 作者:行者123 更新时间:2023-11-30 19:37:29 26 4
gpt4 key购买 nike

我有一个扩展方法,可以根据日期期间类型计算截止日期。该方法如下所示:

public static DateTime CalculateDueDate(this DateTime date, OffsetType offsetType, int offset)
{
switch (offsetType)
{
case OffsetType.Days:
return date.AddDays(offset);
case OffsetType.Weeks:
return date.AddWeeks(offset);
case OffsetType.Months:
return date.AddMonths(offset);
default:
throw new ArgumentOutOfRangeException("offsetType", offsetType, null);
}
}

其中 OffsetType 枚举具有这些可能的值:

public enum OffsetType
{
Months = 1,
Weeks = 2,
Days = 3
}

当未提供(或提供)OffsetType enum 时,如何确保抛出 ArgumentOutOfRangeException无效值)?如果 OffsetType 参数不是 null,我是否还需要担心对异常进行单元测试?

更新:

我希望我可以投票支持多个答案。我决定使用 Lee 建议的超出范围的值和 dasblinkenlight .这是我的鳍单元测试:

    [Test]
public void CalculateDueDate_Throw_Exception_Test()
{
var date = DateTime.Now;
var period = 3;
var offsetType = (OffsetType) (-1);

Assert.Throws<ArgumentOutOfRangeException>(() => date.CalculateDueDate(offsetType, period));
}

最佳答案

您可以将超出范围的值强制转换为枚举类型:

Assert.Throws<ArgumentOutOfRangeException>(() => {
CalculateDueDate(date, (OffsetType)(-1), offset);
});

您可以使用哪些值取决于枚举的基础类型。

关于c# - 如何对空枚举进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37972266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com