简体   繁体   中英

Issue in catching the thrown exception in Unit Test Case

I have a method that takes an argument Source Folder / Source File.I have handled the code in such a way that if Source Folder or Source File does not exist , it should throw DirectoryNotFound Exception or FileNotFound Exception accordingly. Following is the Code Snippet

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

While trying to unit test this method for negative scenario ie providing a folder that does not exist, [ExpectedException(typeof(DirectoryNotFoundException))] fails in unit test case. But the actual code responds properly by throwing the appropriate exceptions based on the inputs.

Thanks in advance

Normally, you could write two distinct tests, one for the file case, and one for the directory case.

Anyway, this code does very likely not behave as you expect. The code snippet you posted will always throw if either a file or a directory exists at sourceFileorFolder path.

If the path exists as a file, you throw DirectoryNotFoundException , else you throw a FileNotFoundException . Only if the file does not exist you proceed without throwing.

EDIT: I missed the ! in the big if statement. Actually this method never throws, because the first if statement is entered only if the file does not exist ( not ((folder and not file) or (file and not a folder)) is the same as not (file or folder) ). The smaller if statements behave as I have written above.

no need to go this complex, remove the upper if condition

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

if (isSourceExist == false)
     throw new DirectoryNotFoundException();
else if (isFileExist == false)
     throw new FileNotFoundException();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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