Last active
January 2, 2016 17:29
-
-
Save moodmosaic/8336765 to your computer and use it in GitHub Desktop.
AutoFixture strategy for invoking Factory Methods with most parameters based on Twitter discussion on https://twitter.com/madstt/status/420850414641090560
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class GreedyFactoryMethodQuery : IMethodQuery | |
{ | |
public IEnumerable<IMethod> SelectMethods(Type type) | |
{ | |
if (type == null) | |
throw new ArgumentNullException("type"); | |
return from mi in type.GetMethods( | |
BindingFlags.Static | BindingFlags.Public) | |
where mi.ReturnType == type | |
let parameters = mi.GetParameters() | |
orderby parameters.Length descending | |
select new StaticMethod(mi) as IMethod; | |
} | |
} | |
public class ATypeWithFactoryMethods | |
{ | |
private ATypeWithFactoryMethods() | |
{ | |
} | |
public static ATypeWithFactoryMethods Create() | |
{ | |
return new ATypeWithFactoryMethods(); | |
} | |
public static ATypeWithFactoryMethods Create(object argument) | |
{ | |
return new ATypeWithFactoryMethods(); | |
} | |
} | |
[Fact] | |
public void Test() | |
{ | |
var fixture = new Fixture(); | |
fixture.Customizations.Add( | |
new MethodInvoker( | |
new GreedyFactoryMethodQuery())); | |
var result = fixture.Create<ATypeWithFactoryMethods>(); | |
// -> AutoFixture invokes the static Factory Method with most parameters. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment