I've tried using the AutoMoqCustomizationto auto-mock an object graph with nested dependencies and results are not as I expected. Here's the test code, can someone please tell me why after freezing a Mock<IObject> there's a situation where another IObjectcreated by Moq is created by the fixture?
[TestClass]
public class MyTestClass
{
[TestMethod]
public void Test()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var objMock = fixture.Freeze<Mock<IObject>>();
var sut = fixture.Create<Dependant2>();
sut.Obj.Should().BeSameAs(objMock);
}
}
public interface IObject { }
public interface IDependant { IObject Obj { get; } }
public class MyObject : IObject { }
public class Dependant2
{
public Dependant2(IDependant dependant)
{
Obj = dependant.Obj;
}
public IObject Obj { get; }
}
The AutoMoqCustomization creates mock objects but does not set them up.
If you want the mock's members to be set up, consider using the AutoConfiguredMoqCustomization instead. It'll a) set the mock's public settable properties and b) setup methods/indexers to return (and memoize) values lazily generated by the fixture
There are two limitations. It doesn't setup:
ref parametersMore info at the bottom of the cheat sheet.
Thanks for fast response! I tried AutoConfiguredMoqCustomization with method instead of property in IDependant and it respected the frozen instance. Is there a way to make non-settable properties to be respected as well? With Moq one can setup a property getter even when there's no setter.
Actually, nevermind. It does setup get-only properties too, my bad.
I also remember a bug in Moq that interfered with AutoMoq, making it unable to setup get-only properties. At least back when I looked into this, you had to use Moq version 4.2.1409.1722 or lower (details at #434). Maybe the bug has been fixed in newer version of Moq, I'm not sure.
Tried the highest Moq version that is lower than 4.2.1409.1722 and you're correct, it works for get-only properties as well. The Moq bug wasn't fixed in a newer version, since I tried it with latest. Thank you very much for your help
Duplicates http://stackoverflow.com/q/36656741/126014
Most helpful comment
The
AutoMoqCustomizationcreates mock objects but does not set them up.If you want the mock's members to be set up, consider using the
AutoConfiguredMoqCustomizationinstead. It'll a) set the mock's public settable properties and b) setup methods/indexers to return (and memoize) values lazily generated by the fixtureThere are two limitations. It doesn't setup:
refparametersMore info at the bottom of the cheat sheet.