The example, in the documentation, for mocking mscorlib types assumes that you have direct access to the object you want to mock from the unit test. However, I'm trying to mock a filesystem scenario and the code that I'm testing creates its own instance of the DirectoryInfo type that I want to mock.
Here's what my code looks like:
I want to test the scenario where the Visual Studio folder cannot be found on my disk. The way I thought I could do this, looks like this:
Obviously, that instance of "folder" in my test method isn't being used for anything other than the Arrange statement... I knew as I was writing that, that this wasn't going to work; but, I can't figure out how this test should be constructed.
Can anyone help?
Thanks!
Here's what my code looks like:
public
class
TypeBeingTested
{
public
TypeBeingTested()
{
var folder =
new
DirectoryInfo(
"C:\\Program Files"
);
var folders = folder.GetDirectories(
"Microsoft Visual Studio 8"
);
if
(folders.Length == 0)
throw
new
DirectoryNotFoundException(
"Visual Studio 2005 is not installed."
);
}
}
I want to test the scenario where the Visual Studio folder cannot be found on my disk. The way I thought I could do this, looks like this:
[TestInitialize]
public
void
Mock_DirectoryInfo()
{
Mock.Partial<DirectoryInfo>().For<
string
>((folder, name) => folder.GetDirectories(name));
}
[TestMethod]
[ExpectedException(
typeof
(DirectoryNotFoundException))]
public
void
Missing_Program_Files_folder_throws_exception()
{
var folder =
new
DirectoryInfo(
"C:\\Program Files"
);
Mock.Arrange(() => folder.GetDirectories(
"Microsoft Visual Studio 8"
)).Returns(
new
DirectoryInfo[] {});
var instance =
new
TypeBeingTested();
Assert.Fail(
"No exception was raised in TypeBeingTested constructor."
);
}
Obviously, that instance of "folder" in my test method isn't being used for anything other than the Arrange statement... I knew as I was writing that, that this wasn't going to work; but, I can't figure out how this test should be constructed.
Can anyone help?
Thanks!