5

I have a type and want to create an instance of it with test data.

I know that frameworks like NBuilder or AutoFixture can create instances of types that are known on design time (<T>). Are those frameworks able to create an instance based on a type that is only known at runtime (Type)?

On the end I want to do something like:

var value = Builder.Create(type);
var constant = Expression.Constant(value, type);
Rookian
  • 19,841
  • 28
  • 110
  • 180

1 Answers1

6

AutoFixture does indeed support this. But, as far as I know, there are no convenience extension methods to do this.

The following generic code:

var value = fixture.CreateAnonymous<MyType>();

would look like this with a type only known at runtime:

var context = new SpecimenContext(fixture.Compose());
var value = context.Resolve(new SeededRequest(typeof(MyType), null))
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • That works :) Is it possible to register an implementation of an interface for AutoFixture when AutoFixture tries to create an instance for a property where the type is an interface? – Rookian Oct 17 '12 at 16:24
  • 1
    Yes, that's possible. Please ask it as a seperate question. I will answer it there. – Daniel Hilgarth Oct 17 '12 at 16:27
  • Take a look at: http://stackoverflow.com/questions/12949417/register-an-implementation-of-an-interface-for-autofixture – Rookian Oct 18 '12 at 07:34
  • 2
    There is no `fixture.Compose()` method in my version of AutoFixture – Andrei Jan 16 '16 at 17:42