How to mock a constructor with JustMock?

I am 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 this to 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 it does not work, it seems that fakeDirectoryInfo is not returned in the constructor. How do I pass the test? (I should not change the source code as working code, if possible).

I read something about the future of ridicule and the use of DoNothing (), but I'm not sure if this applies to my own situation.

Thanks in advance.

+4
source share
1 answer

For future reference:

Unfortunately, placing a return value while intercepting a constructor is not possible with

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

If you do not need to distinguish between instances, you can use something like:

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

.IgnoreInstance(). :

Mock.Arrange(() => fakeDirectoryInfo.EnumerateDirectories()).IgnoreInstance().Returns(new DirectoryInfo[] { });
+2

Source: https://habr.com/ru/post/1526753/


All Articles