I'm using MSTest to write test cases for my application.
I have a method where files are moved from one directory to another directory. Now when I run code coverage, it shows that the catch block is not covered in code coverage.
This is my code as below.
class Class1
{
public virtual bool MoveFiles( string fileName)
{
bool retVal = false;
try
{
string sourcePath = "PathSource";
string destinationPath = "DestPath";
if (Directory.Exists(sourcePath) && Directory.Exists(destinationPath))
{
string finalPath = sourcePath + "\\" + fileName ;
if (Directory.Exists(finalPath))
{
File.Move(finalPath, destinationPath);
retVal = true;
}
}
}
catch (Exception ex)
{
LogMessage("Exception Details: " + ex.Message);
retVal = false;
}
return retVal;
}
}
The test method for the above code is this.
[TestMethod()]
public void MoveFilesTest()
{
string filename = "test";
Class1 serviceObj = new Class1();
var result = serviceObj.MoveFiles(filename);
Assert.IsTrue(result);
}
When I run my code coverage, it shows only the try block is covered and not the catch block. So in order to do that, I need to write another test method and generate an exception and test method will look something like this.
[TestMethod()]
public void MoveFilesTest_Exception()
{
string filename = "test";
Class1 serviceObj = new Class1();
ExceptionAssert.Throws<Exception>(() => serviceObj.MoveFiles(filename));
}
Can anyone help to create an exception for this code as I couldn't do that or at least guide me how to do it?
Many thanks!