【问题标题】:Autofixture: Randomly fill property of a classAutofixture:随机填充类的属性
【发布时间】:2022-01-01 07:49:16
【问题描述】:

关于以下课程:

public partial class ByValueCondition 
{       
    public ParameterCondition ParameterCondition { get; set; }
    
    public TimeOfDayCondition TimeOfDayCondition { get; set; }
    
    public SimulationTimeCondition SimulationTimeCondition { get; set; }
    
    public StoryboardElementStateCondition StoryboardElementStateCondition { get; set; }
    
    public UserDefinedValueCondition UserDefinedValueCondition { get; set; }
    
    public TrafficSignalCondition TrafficSignalCondition { get; set; }
    
    public TrafficSignalControllerCondition TrafficSignalControllerCondition { get; set; }
}

我想要在 autofixture 中进行自定义,它只会随机选择一个属性并填充它,而将其他属性留空。底层类的配置仍应由夹具的全局自定义定义。

还应该可以创建 ByValueCondition 的集合。

我对此进行了尝试,但除了从头开始创建 ISpecimenbuilder 之外,找不到简单的解决方案。

【问题讨论】:

    标签: c# autofixture


    【解决方案1】:

    我会亲自使用以下架构:

    // Interface implemented by all Conditions
    public interface ICondition
    {
        bool IsConditionTrue(object ObjectThatWeKnow);
    }
    
    // Your object 
    public partial class ByValueCondition 
    {       
        public ICondition Condition { get; set; }
    }
    
    // And here you define all types of conditions
    public class ParameterCondition : ICondition
    {
        public object Parameter { get; set; }
    
        public bool IsConditionTrue(object ObjectThatWeKnow)
        {
            return ObjectThatWeKnow.Equals(Parameter);
        }
    }
    
    public class TimeOfDayCondition : ICondition
    {
        public bool IsConditionTrue(object ObjectThatWeKnow) { return true; }
    }
    
    public class SimulationTimeCondition : ICondition
    {
        public bool IsConditionTrue(object ObjectThatWeKnow) { return true; }
    }
    

    你可以这样做的随机性:

    var conditions = new List<ICondition>()
    {
        new ParameterCondition() { Parameter = "whatever" },
        new ParameterCondition() { Parameter = "otherString" },
        new ParameterCondition() { Parameter = "NextOne" },
    
        new TimeOfDayCondition() { TimeBefore = DateTime.Now },
        new TimeOfDayCondition() { TimeAfter = DateTime.Now.AddDays(-1) },
    }
    
    var rand = new Random();
    var randomN = rand.Next(0, conditions.Count);
    
    var byValueCondition = new ByValueCondition();
    byValueCondition.Condition = conditions[randomN]; //Here you assign random value
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多