Search code examples
xunit.netfscheck

Is FSCheck suitable for testing type construction?


Background:

I have a large number of commands that satisfy following rules:

  1. no setters (immutable)
  2. one constructor
  3. parameter name matches the name of the property being set (other than casing)

I would like to write a tester that tests following

  1. given that all arguments are provided I get an instance of the class, and that all properties are set to the value passed.
  2. given that any one of the reguired parameters is either null, empty etc. based on the type constructor raises argument exception.

Now, I can write this via reflection, hand roll it, no problem, but I was wondering if I could tap into FsCheck generators to generate parameters.

Is this something that I could achieve with FSCheck?


Solution

  • Yes it can. In fact, if FsCheck can generate the types of the arguments (i.e. if they are primitive types like string or int, or can be generated reflectively), then from your description FsCheck can already generate these types out of the box without you doing anything.

    For example, a type like this: (I'm assuming you're using C#)

    public class Foo {
        public string A { get; }
        public int[] B { get; }
        public Foo(string a, int[] b) {
           A = a;
           B = b;
        }
    }
    

    can be generated by FsCheck, you can write an xunit test with FsCheck.Xunit as follows:

    [Property]
    public void FooTest(Foo oneRandomFoo, Foo[] manyRandomFoos) {
        // assert something about the foos
    }
    

    And FsCheck will generate a bunch of random Foo instances for you.