AutoFixture - how do I call a method, how to set a private setter of an autoproperty?

醉酒当歌 提交于 2020-01-03 18:51:29

问题


Here's my class:

public MyClass {
  public int Id { get; private set; }
  public SetAssignableId (int id) {
    this.Id = id;
  }
}

I would like to have AutoFixture set the Id via SetAssignableId or the private setter.


回答1:


There's no way to invoke a private setter with AutoFixture today. Although it uses reflection internally, by design it respects a type's public API.

There's an outstanding request on the Issue Board to make this more customizable - if you read the work item closely you will see that there's a request to enable filling of protected setters.

However, with the example given, it's certainly possible to invoke the SetAssignableId method. A Customization like this should do the trick:

fixture.Customize<MyClass>(c => 
    c.Do(mc => 
        mc.SetAssignableId(fixture.CreateAnonymous<int>())));


来源:https://stackoverflow.com/questions/5722581/autofixture-how-do-i-call-a-method-how-to-set-a-private-setter-of-an-autoprop

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