How to generate a stub object of an arbitrary Type not known at compile time using AutoFixture
Asked Answered
W

1

6

I can get type of constructor parameter like this:

Type type = paramInfo.ParameterType;

Now I want to create stub object from this type. Is is possible? I tried with autofixture:

public TObject Stub<TObject>()
{
   Fixture fixture = new Fixture();   
   return fixture.Create<TObject>();
}

.. but it doesn't work:

Type type = parameterInfo.ParameterType;   
var obj = Stub<type>();//Compile error! ("cannot resolve symbol type")

Could you help me out?

Worden answered 23/9, 2013 at 7:20 Comment(7)
Does autofixture have a non-generic API at all? Switching between reflection (Type) and generics (<T>) is ... kinda painful (and slow) - you can do it (with yet more reflection) - but it is best avoided if at all possible...Alphorn
Seems like AutoFixture does not provide an easy solution for this problem: thomasardal.com/…Homoousian
Is it possible anyway to create stub with Type? (with or without autofixture)Worden
Sure, most basically with Reflection. NSubsitute has measures for that as well: nsubstitute.github.io/help/creating-a-substituteHomoousian
The answer provided by Enrico Campidoglio is correct, but why do you want to do that in the first place? It sounds like you're attempting to automate your use of AutoFixture (which is fine), but there are probably better better, more idiomatic ways of doing it...Blythe
@Mark Seemann My goal was the next: my service classes each have some dependencies (injected via constructor). Every method in this service class uses only few of this dependencies. So in unit test when I test some method I don't want to create test class every time with all dependencies, but I want to replace the dependencies which are not used in tested method by stubs. My aim was to automate services creation and I put this creation into a separate base unit test. I would appreciate if you suggest me a better ways )Worden
You can easily turn AutoFixture into an Auto-mocking Container. See e.g. this answer for an overview: https://mcmap.net/q/826637/-autofixture-as-an-automocking-container-vs-automocking-differencesBlythe
E
11

AutoFixture does have a non-generic API to create objects, albeit kind of hidden (by design):

var fixture = new Fixture();
var obj = new SpecimenContext(fixture).Resolve(type);

As the blog post linked by @meilke points out, if you find yourself needing this often, you can encapsulate it in an extension method:

public object Create(this ISpecimenBuilder builder, Type type)
{
    return new SpecimenContext(builder).Resolve(type);
}

which allows you to simply do:

var obj = fixture.Create(type);
Ernestoernestus answered 23/9, 2013 at 7:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.