在单元测试用例中捕获引发的异常的问题

时间:2018-08-13 04:59:17

标签: c# unit-testing

我有一个方法接受参数Source Folder / Source File。我已经处理了这样的代码,如果Source Folder或Source File不存在,它将相应地抛出DirectoryNotFound Exception或FileNotFound Exception。 以下是代码段

          Boolean isSourceExist = Directory.Exists(sourceFileorFolder);
          Boolean isFileExist = File.Exists(sourceFileorFolder);
            if (!(
                ((isSourceExist == true) && (isFileExist == false)) ||
                ((isSourceExist == false) && (isFileExist == true))
               ))
            {
                if (isSourceExist == false)
                    throw new DirectoryNotFoundException();
                else if (isFileExist == false)
                    throw new FileNotFoundException();
            }

虽然尝试对否定方案进行此方法的单元测试,即提供一个不存在的文件夹,但是[ExpectedException(typeof(DirectoryNotFoundException))]在单元测试用例中失败。 但是实际的代码会根据输入抛出适当的异常,从而正确响应。

预先感谢

2 个答案:

答案 0 :(得分:0)

通常,您可以编写两个不同的测试,一个用于文件大小写,另一个用于目录大小写。

无论如何,此代码很可能不会像您期望的那样运行。如果文件或目录位于sourceFileorFolder路径中,则您发布的代码段将始终抛出。

如果路径以文件形式存在,则抛出DirectoryNotFoundException,否则抛出FileNotFoundException。仅当文件不存在时,您才继续进行而不抛出。

编辑:我错过了大!语句中的if。实际上,此方法永远不会抛出异常,因为仅当文件不存在时输入第一个if语句(不((文件夹和非文件)或(文件而不是文件夹)是与不是(文件或文件夹))相同。较小的if语句的行为与我上面所写的相同。

答案 1 :(得分:0)

无需复杂,删除条件为上的

Boolean isSourceExist = Directory.Exists(sourceFileorFolder);
Boolean isFileExist = File.Exists(sourceFileorFolder);

if (isSourceExist == false)
     throw new DirectoryNotFoundException();
else if (isFileExist == false)
     throw new FileNotFoundException();
相关问题