I would like to use Autofixture to create an instance of a class which I am consuming from a 3rd party library.
the problem I am facing is that the constructor of this class has an internal access modifier, and being from a 3rd party solution I cant really use the InternalsVisibleTo attribute, so I was wondering if there is any Autofixture behaviour that can be used or if there are any alternative techniques that can be applied in these kind of scenarios.
public class RecordedEvent
{
/// <summary>The Event Stream that this event belongs to</summary>
public readonly string EventStreamId;
/// <summary>The Unique Identifier representing this event</summary>
public readonly Guid EventId;
/// <summary>The number of this event in the stream</summary>
.....
internal RecordedEvent(....)
{
.....
}
}
OOTB, AutoFixture tries to find a public constructors or static factory method which is able to create an instance of a class. Since you do not own RecordedEvent
and cannot add public constructor, you have to teach AutoFixture how to instantiate it. There is mechanism called Customizations that can be used for that.
First of all you create a customization which is able to find all the internal constructors for a type:
public class InternalConstructorCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<RecordedEvent>(c =>
c.FromFactory(
new MethodInvoker(
new InternalConstructorQuery())));
}
private class InternalConstructorQuery : IMethodQuery
{
public IEnumerable<IMethod> SelectMethods(Type type)
{
if (type == null) { throw new ArgumentNullException(nameof(type)); }
return from ci in type.GetTypeInfo()
.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)
select new ConstructorMethod(ci) as IMethod;
}
}
}
then you apply it to your Fixture
:
var fixture = new Fixture()
.Customize(new InternalConstructorCustomization());
and after that you can create instances of the RecordedEvent
class:
var recordedEvent = fixture.Create<RecordedEvent>(); // does not throw