I have a data type with multiple constructors and I need AutoFixture to choose the greediest (one with the most parameters). The default behaviour is to choose the constructor with the smallest number.
The author’s blog post, http://blog.ploeh.dk/2009/03/24/HowAutoFixtureCreatesObjects.aspx doesn’t seem to imply there’s a way of overriding this behaviour, so is it possible, and if so, how?
This is certainly possible.
To change the strategy for a single type (
MyClass):To change the strategy across the board:
As it turns out, however, using GreedyConstructorQuery across the board is most likely problematic, as the following code snippet demonstrates. Imagine a class with this constructor:
This test will throw an exception:
The exception thrown is:
So what’s that about the SByte*? There’s no SByte* in Foo…
Well, yes there is. By placing the MethodInvoker in Customization, it overrides all default creation strategies, including the one for strings. Instead, it goes looking for the greediest constructor for string and that is:
And there’s the sbyte*…
It’s still possible to replace the modest constructor selection algorithm with a greedy algorithm, it’s just a tad more involved than I first realized.
What you can do is this:
Write a small class like this one:
and create the Fixture instance like this:
That should work.