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

丶灬走出姿态 提交于 2021-02-07 21:09:14

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/17421739/autofixture-unable-to-create-an-instance-probably-no-public-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!