相关疑难解决方法(0)

为什么这个字符串扩展方法不会抛出异常?

我有一个C#字符串扩展方法,它应返回IEnumerable<int>字符串中子字符串的所有索引.它完美地用于其预期目的,并返回预期的结果(由我的一个测试证明,虽然不是下面的一个),但另一个单元测试发现它有一个问题:它不能处理空参数.

这是我正在测试的扩展方法:

public static IEnumerable<int> AllIndexesOf(this string str, string searchText)
{
    if (searchText == null)
    {
        throw new ArgumentNullException("searchText");
    }
    for (int index = 0; ; index += searchText.Length)
    {
        index = str.IndexOf(searchText, index);
        if (index == -1)
            break;
        yield return index;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是标记问题的测试:

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Extensions_AllIndexesOf_HandlesNullArguments()
{
    string test = "a.b.c.d.e";
    test.AllIndexesOf(null);
}
Run Code Online (Sandbox Code Playgroud)

当测试针对我的扩展方法运行时,它会失败,标准错误消息表明该方法"没有抛出异常".

这很令人困惑:我已明确传入null函数,但由于某种原因,比较null == null正在返回false.因此,不会抛出异常并且代码会继续.

我已经确认这不是测试的错误:在我的主项目中通过调用Console.WriteLinenull比较if块运行该方法时,控制台上没有显示任何内容,并且catch我添加的任何块都没有捕获到任何异常.而且,使用string.IsNullOrEmpty而不是== null …

c# comparison ienumerable null argumentnullexception

117
推荐指数
2
解决办法
6609
查看次数