AutoFixture constrained string parameter

后端 未结 1 377
囚心锁ツ
囚心锁ツ 2021-01-23 21:18

Is there a simple way to specify a list of possible values for the parameter orderBy? Not one by one please, otherwise I would not be making the question. I want to specify that

相关标签:
1条回答
  • 2021-01-23 22:11

    If I understand the question correctly, the problem is that the orderBy value should be randomly selected from a list of predefined values, but that list might be too large to use with [InlineAutoData].

    The easiest way to do this that I can think of is to introduce a helper type. This might actually be a valuable addition to the application code itself, as it makes the role of various values more explicit, but if not, you can always add the wrapper type to the test code base.

    Something like this is the minimum you'll need:

    public class OrderCriterion
    {
        public OrderCriterion(string value)
        {
            Value = value;
        }
    
        public string Value { get; }
    }
    

    If we also imagine that this class exposes a list of ValidValues, you can implement an AutoFixture Customization using the ElementsBuilder class:

    public class OrderCriterionCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Customizations.Add(
                new ElementsBuilder<OrderCriterion>(OrderCriterion.ValidValues));
        }
    }
    

    Then you create a data source attribute for your test code base:

    public class TestConventionsAttribute : AutoDataAttribute
    {
        public TestConventionsAttribute() : base(
            () => new Fixture().Customize(new OrderCriterionCustomization()))
        {
        }
    }
    

    This enables you to write a test like this, which passes:

    [Theory, TestConventions]
    public void IndexReturnsView(
        int? pageIndex,
        int? pageSize,
        OrderCriterion orderBy,
        bool? desc)
    {
        Assert.Contains(orderBy.Value, OrderCriterion.ValidValues.Select(x => x.Value));
    }
    

    Notice that instead of declaring the orderBy parameter as a string, you declare it as an OrderCriterion, which means that AutoFixture will be detect its presence, and the Customization then kicks in.

    See also https://stackoverflow.com/a/48903199/126014

    0 讨论(0)
提交回复
热议问题