I have an object model that uses Open Generics (Yes, yes, now I have two problems; that's why I'm here :) :-
public interface IOGF<T>
{
}
class C
{
}
class D
{
readonly IOGF<C> _ogf;
public D( IOGF<C> ogf )
{
_ogf = ogf;
}
}
I'm trying to get AutoFixture to generate Anonymous instances of D
above. However, on its own, AutoFixture doesn't have a built in strategy for building an IOGF<>
and hence we observe:
public class OpenGenericsBinderDemo
{
[Fact]
public void X()
{
var fixture = new Fixture();
Assert.Throws<Ploeh.AutoFixture.ObjectCreationException>( () =>
fixture.CreateAnonymous<D>() );
}
The underlying message is:
Ploeh.AutoFixture.ObjectCreationException : AutoFixture was unable to create an instance from IOGF`1[C], most likely because it has no public constructor, is an abstract or non-public type.
I'm happy to provide it a concrete implementation:
public class OGF<T> : IOGF<T>
{
public OGF( IX x )
{
}
}
public interface IX
{
}
public class X : IX
{
}
And an associated binding:
fixture.Register<IX,X>();
How do I (or should I even look at the problem that way??) make the following test pass?
public class OpenGenericsLearning
{
[Fact]
public void OpenGenericsDontGetResolved()
{
var fixture = new Fixture();
fixture.Inject<IX>( fixture.Freeze<X>() );
// TODO register or do something that will provide
// OGF<C> to fulfill D's IOGF<C> requirement
Assert.NotNull( fixture.CreateAnonymous<D>());
}
}
(There are discussions and issues around this on the codeplex site - I just needed to a quick impl of this and am open to deleting this if this is just a bad idea and/or I've missed something)
EDIT 2: (See also comment on Mark's answer) The (admittedly contrived) context here is an acceptance test on a large 'almost full system' System Under Test object graph rather than a small (controlled/easy to grok :) pair or triplet of classes in a unit or integration test scenario. As alluded to in the self-question parenthetical statement, I'm not fully confident this type of test even makes sense though.
You could create a customization which works as follows:
And is implemented like so:
I assume someone has a better implementation than that though and/or there is a built-in implementation.
EDIT: The following is the updated D with the sensing property:
AFICT there are no open generics in sight.
D
relies onIOGF<C>
which is a constructed type.The error message isn't because of open generics, but because
IOGF<C>
is an interface.You can supply a mapping from
IOGF<C>
toOGF<C>
like this:Since
OGF<C>
relies onIX
you'll also need to supply a mapping toX
:That should do the trick.
However, as Nikos Baxevanis points out in his comment, if you use one of the three supplied auto-mocking extensions, this would basically work out of the box - e.g.