How to mock a constructor with JustMock?
Asked Answered
M

1

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.

Mahaliamahan answered 13/2, 2014 at 14:23 Comment(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: feedback.telerik.com/Project/105/Feedback/Details/…Crystacrystal
M
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[] { });
Mahaliamahan answered 17/2, 2014 at 19:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.