6

I'm trying to test the following code:

public ICollection<RawCatalog> ReadCatalog(string familyName)
{
    // Root folder for the family
    string familyFolder = this.GetFamilyFolder(familyName);
    DirectoryInfo familyFolderInfo = new DirectoryInfo(familyFolder);

    foreach (DirectoryInfo subFamilyFolderInfo in familyFolderInfo.EnumerateDirectories())
    {
        // Do stuff
    }
}

I expected that this would work:

// Arrange
DirectoryInfo fakeDirectoryInfo = Mock.Create<DirectoryInfo>(Constructor.Mocked);
Mock.Arrange(() => new DirectoryInfo(@"testRoot\DrivesData\TestFamily")).Returns(fakeDirectoryInfo);
Mock.Arrange(() => directoryInfo.EnumerateDirectories()).Returns(new DirectoryInfo[] { });

But is not working as seems that fakeDirectoryInfo is not being returned in the constructor. How should I do the test? (I should not change the source code as it's working code if possible).

I've read something about future mocking and using DoNothing() but not sure if this apply to my own situation.

Thanks in advance.

Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207
  • 1
    Arranging the return value of `new` expressions is pretty high on our list of features-to-be, but it wouldn't hurt if you voted for it in the JustMock feedback portal: http://feedback.telerik.com/Project/105/Feedback/Details/126623-arrange-return-value-of-new-expressions – Stefan Dragnev Apr 23 '14 at 09:15

1 Answers1

6

For future reference:

Unfortunately, arranging a return value on a constructor interception is not possible with

JustMock.Mock.Arrange(() => new DirectoryInfo(@"testRoot\DrivesData\TestFamily")).Returns(fakeDirectoryInfo);)

If you don't need to differentiate instances you can use something like:

Mock.Arrange(() => new DirectoryInfo(passedString)).DoNothing();

And on the arrange calls use the .IgnoreInstance() method. This should result in a call like:

Mock.Arrange(() => fakeDirectoryInfo.EnumerateDirectories()).IgnoreInstance().Returns(new DirectoryInfo[] { });
Ian
  • 33,605
  • 26
  • 118
  • 198
Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207