Search code examples
c#autofixturenbuilder

Is there a way of creating an instance of a type with test data?


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);

Solution

  • 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))