问题
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