I have a problem with a unit test. I fill objects with AutoFixture and some of the objects have ICloneable objects somewhere in the hierarchy. The test is completely generic, so I need a solution that does not need to know concrete types in advance.
AutoFixture seem to generate some default implementation of ICloneable.Clone() methods which returns an object of type System.Object which then causes InvalidCastException in the code.
It is a common pattern to cast the return type of Clone to the declaring type in our codebase, so I need a generic customisation for AutoFixture that creates appropriate implementations for all ICloneable.Clone() methods found in the object hierarchy.
I had posted this question some timeago but it was closed because I provided no reproduciable sample. But now here is:
[TestClass]
public class CloneMock
{
public abstract class Foo : ICloneable
{
public abstract object Clone();
}
public class Bar
{
public Foo Foo { get; set; }
public void CloneTheFoo()
{
this.Foo = (Foo)this.Foo.Clone(); // this throws
}
}
[TestMethod]
public void SomeTest()
{
var f = new Fixture();
f.Customize(new AutoMoqCustomization());
var c = f.Create<Bar>();
c.CloneTheFoo();
}
}
This code leads to the following error:
System.InvalidCastException:
Unable to cast object of type ‘Castle.Proxies.ObjectProxy’ to type
‘Foo’.
at Zeiss.Micro.LSM.Tests.Utilities.CloneMock.Bar.CloneTheFoo()