简体   繁体   English

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

[英]Issue with Assert.Throws Exception in NUnit testing

I am trying out NUnit, Unit Testing and Integration testing for the first time. 我是第一次尝试NUnit,单元测试和集成测试。 I have been reading up and doing lots of online courses. 我一直在阅读并做很多在线课程。 As I'm sure you know very well it's something knowing theory and doing it in practice. 我相信您非常了解,这是了解理论并在实践中进行的工作。

I am stuck on a particular test. 我被困在特定的测试中。 The application that I have is in C# .Net 3.5. 我拥有的应用程序在C#.Net 3.5中。

I am trying to assert that a method with a certain bad input will throw a particular exception. 我试图断言具有错误输入的方法将引发特定异常。 When I run the method with the same input given to the test the expected exception is thrown. 当我使用与测试相同的输入来运行该方法时,将引发预期的异常。

The method being tested code is: 被测试的方法代码为:

 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;
}

I want to check that the above code can catch an exception if the provided input directory is not meeting the criteria. 如果提供的输入目录不符合条件,我想检查以上代码是否可以捕获异常。

The Unit test that I have at the moment is: 我目前的单元测试是:

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

        Assert.Throws<ArgumentNullException>(() => sut.FilePathHasInvalidChars(testDirectory));
    }

The problem I have is that the test allways fails and if I check the return it states that It expected an ArgumentNull exception but was null. 我的问题是测试始终失败,并且如果我检查返回值,它会指出它期望ArgumentNull异常,但为null。 I have taken a screenshot of the output from the test: 我已经截取了测试输出的屏幕截图: 抛出测试输出

Any idea what I might be doing wrong? 知道我做错了什么吗? EDIT: By the way I have also attempted to use 编辑:顺便说一句我也尝试使用

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

Have had same result with that. 产生了相同的结果。

On an ending note I am not sure if this is considered an Integration test or a Unit test given that my method uses Path.GetFullPath(string directory). 最后,我不确定这是集成测试还是单元测试,因为我的方法使用Path.GetFullPath(string directory)。 Anyway my main issue right now is understanding what I am doing wrong. 无论如何,我现在的主要问题是了解我在做什么错。 :) :)
Many thanks, Jetnor. 非常感谢Jetnor。

UPDATE: After taking all the points into consideration and looking at my system's needs I have decided not to throw an exception. 更新:在考虑了所有要点并考虑了系统的需求之后,我决定不抛出异常。 Instead I have decided to create tests which cover the different possible exceptions that can occur in my situation. 相反,我决定创建测试以涵盖在我的情况下可能发生的各种可能的异常。 The test method looks like this: 测试方法如下:

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

This is a starting point. 这是一个起点。 I inted to use the [TestCase] option by providing all the inputs to one test and checking all of them at the same time. 我通过将所有输入提供给一个测试并同时检查所有输入来使用[TestCase]选项。 Thanks for your help guys. 感谢您的帮助。

Your method FilePathHasInvalidChars does not throw an exception. 您的方法FilePathHasInvalidChars不会引发异常。 An exception is thrown inside of your method, but your method catches and handles the exception. 方法内部会引发异常,但是您的方法会捕获并处理该异常。 Your method will always return a valid value. 您的方法将始终返回有效值。

If you want your method to throw an ArgumentNullException rather than logging and swallowing it, try this: 如果要让您的方法抛出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;
}

With this modification, if userInputPath is null your method will log and re-throw the ArgumentNullException, and your unit test will see the exception and pass. 进行此修改后,如果userInputPath为null,则您的方法将记录并重新引发ArgumentNullException,并且您的单元测试将看到异常并通过。

Your code does not throw an ArgumentNullException . 您的代码不会引发ArgumentNullException Based on your code, it should never* throw any exception- it should simply return true or false . 根据您的代码,它永远不会*抛出任何异常-它应该只返回truefalse

Change your test to the NUnit equivalent of: 将测试更改为等效于以下内容的NUnit:

Assert.IsTrue(() => sut.FilePathHasInvalidChars(testDirectory));

Or, if an empty string SHOULD throw an ArgumentNullException, modify the code to something like the following**: 或者,如果一个空字符串应该抛出ArgumentNullException,则将代码修改为类似以下内容的**:

private static bool FilePathHasInvalidChars(string userInputPath)
{
    if(string.IsNullOrWhiteSpace(userInputPath) throw new
        ArgumentNullException("userInputPath");
    try
    {
        Path.GetFullPath(userInputPath);//this is where the warning appears

    }
    catch (ArgumentException 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);
        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;
}

*- For a value of "never" that means "so rarely you're unlikely to have to consider it" *-对于“从不”的值,表示“因此很少您不必考虑它”

**- I haven't tried to compile that, so there may be errors; **-我没有尝试编译它,因此可能会出现错误; it's just a starting point. 这只是一个起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM