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.
With the mockConstruction you can mock calls made to the constructor. For example, we mock the constructor for the class Dog. The test code is inside a try with resources to limit the scope. When your code calls the constructor inside the try statement, it returns a mock object.
There is a third option when using JustMock – create a mock of the concrete NorthWindEntities class that ignores the constructor. As the following code shows, this is extremely simple to do. Specifying Constructor.Mocked when creating the mock will exclude any code inside the constructor from execution and remove the dependency on the database.
To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method.
Static Mocking Static mocking is one of the advanced features supported in Telerik® JustMock. It allows you to fake static constructors, methods and properties calls, set expectations and verify results using the AAA principle. We can divide static mocking into the following major parts:
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[] { });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With