我想將xUnit理論與AutoFixture一起使用來生成匿名對象,但具有某些顯式屬性。使用AutoFixture定製明確設置標本的多個屬性
這是我現在有:
系統下測試
public class Task
{
public TaskState TaskState { get; set;}
public int Progress { get; set; }
}
通用定製
public class PropertyCustomization<T> : ICustomization
{
private readonly string propertyName;
private readonly object value;
public PropertyCustomization(string propertyName, object value)
{
this.propertyName = propertyName;
this.value = value;
}
public void Customize(IFixture fixture)
{
fixture.Customize<T>(cmp => cmp.Do(obj => obj.SetProperty(this.propertyName, this.value)));
}
}
..
public static void SetProperty(this object instance, string propertyName, object value)
{
var propertyInfo = instance.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
propertyInfo.SetValue(instance, value);
}
和屬性使用它
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AutoTaskAttribute : CustomizeAttribute
{
private readonly int progress;
private readonly TaskState taskState;
public AutoTaskAttribute(TaskState taskState, int progress = -1)
{
this.taskState = taskState;
this.progress = progress;
}
public override ICustomization GetCustomization(ParameterInfo parameter)
{
if (parameter == null)
{
throw new ArgumentNullException("parameter");
}
var result = new List<ICustomization> { new PropertyCustomization<Task>("TaskState", this.taskState) };
if (this.progress > -1)
{
result.Add(new PropertyCustomization<Task>("Progress", this.progress));
}
return new CompositeCustomization(result);
}
}
所以,如果我用它來指定像有唯一的國家,它運作良好,並建立匿名任務
[Theory, AutoMoqData]
public void TestSomething([AutoTask(TaskState.InProgress)]Task task)
{...}
但是,如果我想設置州和進步,它才成立第二屬性出於某種原因,儘管兩個「Do」代表都被調用,但在第二次調用中,它再次接收到具有默認狀態的任務。
[Theory, AutoMoqData]
public void TestSomething([AutoTask(TaskState.InProgress, 50)]Task task)
{...}
我懷疑CompositeCustomization多「Do'基於定製的原因,但不知道爲什麼。
你能包括'TaskState'源代碼和'SetProperty'呢? –
「TestSomething」方法如何裝飾? –
我更新了初始文章。 SetProperty只是使用反射來簡單地設置對象的屬性,AutoMoqData屬性應用默認AutoMoqCustomization –