How to use AutoBogus to create fake object of class with constructor parameter?

856 views Asked by At

I have a class say User with interface in constructor paramater. Could someone please help me how I can create fake object with mocked interface.

enter image description here

Right now It is throwing an exception. Is there any way to override it?

1

There are 1 answers

0
AceGambit On

First -- There's a typo in your post title, please fix that so others can find this post.

Second -- This behavior is clearly documented in AutoBogus' Readme, under Binders.

A default IAutoBinder implementation is included with AutoBogus, but it will not generate interfaces or abstract classes. For this, the following packages are available ...

So you're going to want to add one of those NuGet packages to your project and use it to configure your auto generator.

Example, using NSubstitute (my personal favorite C# mocking library):

var user = AutoFaker.Generate<User>(builder => 
  builder.WithBinder(new NSubstituteBinder()));

This injects the User constructor with what essentially amounts to Substitute.For<IValidate>().