Search code examples
fscheckproperty-based-testing

FsCheck: Generate Arbitrary of a ArrayList with its elements as Arbitraries in C#


I am using FsCheck in C#, I want to generate Arbitrary of an ArrayList to do PropertyBasedTesting by having 100's of ArrayList. I have this ArrayList with defined Arbitraries (they cannot be changed) for each element in it -

E.g. System.Collections.ArrayList a = new System.Collections.ArrayList(); a.Add(Gen.Choose(1, 55)); a.Add(Arb.Generate<int>()); a.Add(Arb.Generate<string>())

How do I get an Arbitrary of this ArrayList?


Solution

  • Based on the example linked by Mark Seemann I created a complete compiling example. It doesn't provide much extra compared to the link, but it won't risk being broken in the future.

    using System.Collections;
    using FsCheck;
    using FsCheck.Xunit;
    using Xunit;
    public class ArrayListArbritary
    {
        public static Arbitrary<ArrayList> ArrayList() =>
            (from e1 in Gen.Choose(1, 15)
             from e2 in Arb.Generate<int>()
             from e3 in Arb.Generate<string>()
             select CreateArrayList(e1, e2, e3))
            .ToArbitrary();
    
        private static ArrayList CreateArrayList(params object[] elements) => new ArrayList(elements);
    }
    
    public class Tests
    {
        public Tests()
        {
            Arb.Register<ArrayListArbritary>();
        }
    
        [Property]
        public void TestWithArrayList(ArrayList arrayList)
        {
            Assert.Equal(3, arrayList.Count);
        }
    }