Search code examples
c#autofixture

AutoFixture: Unable to create an instance, probably no public constructor


I have a class (LoginService) that accepts in the constructor an IUser. This is for performing integration tests rather than unit tests, for that reason I don't want to MOCK these, I have some Unit Tests already and they are working great using Moq with fixture.

I setup my fixture:

  var fixture = new Fixture();

And then I want to be able to freeze a version of the IUser, I have tried the following but I couldn't get it to work, it complains that it can't create the instance, probably due to a no constructor.

  var user = fixture.Freeze<IUser>();

So I have managed to get it to work doing the following

  IUser user = new User();  // Create my IUser manually
  fixture.Inject(user);

and then finally create the sut and sure enough the instance is injected.

  var sut = fixture.Create<LoginService>();

So am I doing this correct? Can I not use Freeze and I should continue to create my IUser manually and inject it onto the fixture?


Solution

  • Yes, that's correct – If you want to supply a specific instance of IUser to the LoginService you have to inject it.

    Just keep in mind that Inject will affect all subsequent requests (if any) for IUser.