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

StackOverflow https://stackoverflow.com/questions/17421739

  •  02-06-2022
  •  | 
  •  

سؤال

I seem to be having an issue, 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?

Look forward to any help or information

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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)));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top