Martin
Martin

Reputation: 24316

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?

Upvotes: 3

Views: 3977

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233505

The answer by Nikos Baxevanis is correct, but there are many ways to skin that cat.

If, instead of the same user instance, you want a new instance every time, you could also map User to IUser:

fixture.Customizations.Add(
    new TypeRelay(
        typeof(IUser),
        typeof(User)));

Upvotes: 3

Nikos Baxevanis
Nikos Baxevanis

Reputation: 11211

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.

Upvotes: 4

Related Questions