问题与Assert.Throws NUnit测试中的异常

Jet*_*nor 0 c# integration-testing nunit unit-testing exception-handling

我是第一次尝试NUnit,单元测试和集成测试.我一直在阅读和做很多在线课程.因为我相信你非常清楚这是理解理论并在实践中做到的事情.

我被困在一个特定的测试上.我的应用程序是在C#.Net 3.5中.

我试图断言具有某个错误输入的方法将抛出特定异常.当我使用给测试的相同输入运行方法时,抛出预期的异常.

被测试的方法是:

 private static bool FilePathHasInvalidChars(string userInputPath)
{
    try
    {
        Path.GetFullPath(userInputPath);//this is where the warning appears

    }
    catch (Exception e)
    {
        Log.Error(String.Format(
            "The Program failed to run due to invalid characters or empty string value for the Input Directory. Full Path : <{0}>. Error Message : {1}.",
            userInputPath, e.Message), e);
        return true;

    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我想检查上面的代码是否可以捕获异常,如果提供的输入目录不符合条件.

我目前的单元测试是:

    [Test]
    public void can_throws_exception_for_empty_string()
    {
        var testDirectory = "";
        var sut = new DirectoryInfoValidator();

        Assert.Throws<ArgumentNullException>(() => sut.FilePathHasInvalidChars(testDirectory));
    }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是测试总是失败,如果我检查返回它说明它期望一个ArgumentNull异常但是为null.我从测试中截取了输出的截图: Asstert.Throws测试输出

知道我可能做错了什么吗?编辑:顺便说一句,我也试图使用

[ExpectedException(typeof(ArgumentNullException), ExceptionMessage= "Log Message", MatchType=MessageMatch.Contains)]

与此有相同的结果.

在结尾注释中,我不确定这是否被认为是集成测试或单元测试,因为我的方法使用Path.GetFullPath(字符串目录).无论如何,我现在的主要问题是理解我做错了什么.:)
非常感谢,Jetnor.

更新:考虑到所有要点并查看我的系统需求后,我决定不抛出异常.相反,我决定创建测试,涵盖在我的情况下可能发生的各种可能的异常.测试方法如下所示:

        [Test]
    public void returns_true_for_empty_string()
    {
        var testDirectory = "";
        var sut = new DirectoryInfoValidator();
        var isInvalidPath = sut.FilePathHasInvalidChars(testDirectory);
        Assert.That(isInvalidPath, Is.True);
    }
Run Code Online (Sandbox Code Playgroud)

这是一个起点.我通过为一个测试提供所有输入并同时检查所有输入来使用[TestCase]选项.谢谢你的帮助.

Mar*_*iro 6

您的方法FilePathHasInvalidChars不会引发异常.方法内部会抛出异常,但您的方法会捕获并处理异常.您的方法将始终返回有效值.

如果你希望你的方法抛出ArgumentNullException而不是记录和吞下它,试试这个:

private static bool FilePathHasInvalidChars(string userInputPath)
{
    try
    {
        Path.GetFullPath(userInputPath);//this is where the warning appears

    }
    catch (ArgumentNullException) {
        Log.Error("The Program failed to run due to a null string value for the Input Directory.");
        throw;
    }
    catch (Exception e)
    {
        Log.Error(String.Format(
            "The Program failed to run due to invalid characters or empty string value for the Input Directory. Full Path : <{0}>. Error Message : {1}.",
            userInputPath, e.Message), e);
        return true;

    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

通过此修改,如果userInputPath为null,则您的方法将记录并重新抛出ArgumentNullException,并且您的单元测试将看到异常并通过.