单元测试能确认代码在输入为空、越界、极值或类型不匹配时的具体行为,确保程序不会崩溃并返回预期的默认值或异常。通过编写针对这些边界条件的测试用例,开发者可以验证函数是否处理了所有可能的错误路径,从而提升系统的健壮性。本文将探讨如何处理空集合、无效索引以及数值溢出等常见边界情况。

GetItemById在ID不存在时返回什么
当查询的ID在列表中不存在时,该方法会抛出KeyNotFoundException。这是为了确保调用者明确知道请求的资源缺失,而不是静默返回null导致后续空引用异常。这种设计强制调用者进行显式检查或使用TryGetValue模式。

using System;
using System.Collections.Generic;
public class ItemService
{
private Dictionary<int, string> _items = new Dictionary<int, string>
{
{ 1, "Item A" },
{ 2, "Item B" }
};
public string GetItemById(int id)
{
if (!_items.ContainsKey(id))
{
throw new KeyNotFoundException($"ID {id} not found.");
}
return _items[id];
}
}
// 测试用例:查询不存在的ID
var service = new ItemService();
try
{
var result = service.GetItemById(99);
Console.WriteLine(result); // 不会执行到这里
}
catch (KeyNotFoundException ex)
{
Console.WriteLine(ex.Message); // 输出: ID 99 not found.
}
ProcessList对空列表的处理逻辑
在处理集合时,如果传入空列表,方法应直接返回默认结果(如0或空字符串),而不是尝试访问第一个元素导致IndexOutOfRangeException。这种防御性编程习惯能避免在数据源暂时为空时引发系统故障。

using System;
using System.Collections.Generic;
public class ListProcessor
{
public int SumValues(List<int> numbers)
{
if (numbers == null || numbers.Count == 0)
{
return 0; // 空列表返回0
}
int sum = 0;
foreach (var num in numbers)
{
sum += num;
}
return sum;
}
}
// 测试用例:传入空列表
var processor = new ListProcessor();
int result = processor.SumValues(new List<int>());
Console.WriteLine(result); // 输出: 0
// 测试用例:传入null
result = processor.SumValues(null);
Console.WriteLine(result); // 输出: 0整数加法在最大值附近的行为
当两个正整数相加超过int.MaxValue时,默认情况下会发生溢出并产生负数结果。单元测试需要确认代码是否启用了checked上下文,以便在发生溢出时抛出OverflowException,从而防止静默的数据损坏。这对于财务或计数类应用至关重要。


















