vendredi 29 janvier 2016

Handling Expected exception in Unit Test C#

I wrote a test case for checking file path. In that test case I used Expected exception, then I want to know what happen if the method would not throw the file not found exception.

For example, I run the test case in another system if the given file path exists in the system, the test will go to fail. But it should not be, the test case should be pass always.

How to handle that situation because the Unit test is not dependent anything example should not depend on machine?

Test case...

string sourceFilePath = @"C:\RipWatcher\Bitmap.USF_C.usf";

string targetDirectory = @"C:\UploadedRipFile\";

[Test]
[ExpectedException(typeof(FileNotFoundException))]
public void InvalidSourceFilePathThrowsFileNotFoundException()
{
    logWriter= new Mock<LogWriter>().Object;

    ripfileUploader = new RipFileUploader(logWriter);

    ripfileUploader.Upload(@"D:\RipWatcher\Bitmap.USF_C.usf",       
    targetDirectory);            
}

Method..

public void Upload(string sourceFilePath, string targetFilePath)
{
    if (!File.Exists(sourceFilePath))
    {
        throw new FileNotFoundException(string.Format("Cannot find the file: {0}", sourceFilePath));
    }

    if (!Directory.Exists(targetFilePath))
    {
        throw new DirectoryNotFoundException(string.Format("Cannot find the Directory: {0}", targetFilePath));
    }
    try
    {
        fileCopyEx.CopyEx(sourceFilePath,targetFilePath);               
    }
    catch (Exception ex)
    {
        throw new Exception(string.Format("Failed to move file {0}", sourceFilePath), ex);        
    }          
}

Aucun commentaire:

Enregistrer un commentaire