Skip to content

Instantly share code, notes, and snippets.

@Kralizek
Last active October 18, 2023 08:32
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Kralizek/cfbe28deacdb5c1e57ad1382e9543805 to your computer and use it in GitHub Desktop.
A C# attribute deriving from AutoDataAttribute in AutoFixture.NUnit3 that can be customized per test.
public class SmartAutoDataAttribute : AutoDataAttribute
{
public SmartAutoDataAttribute() : base(() => CreateFixture(null)) { }
public SmartAutoDataAttribute(Type type, string methodName) : base(CreateFixtureWithMethod(type, methodName)) { }
private static Func<IFixture> CreateFixtureWithMethod(Type type, string methodName)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (methodName == null)
{
throw new ArgumentNullException(nameof(methodName));
}
var method = (Action<IFixture>)Delegate.CreateDelegate(typeof(Action<IFixture>), type, methodName);
if (method == null)
{
throw new ArgumentException($"Method '{methodName}' not found in {type.Name}.", methodName);
}
return () => CreateFixture(method);
}
private static IFixture CreateFixture(Action<IFixture> method)
{
var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization
{
ConfigureMembers = true,
GenerateDelegates = true
});
method?.Invoke(fixture);
return fixture;
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" Version="4.8.0" />
<PackageReference Include="AutoFixture.AutoMoq" Version="4.8.0" />
<PackageReference Include="AutoFixture.NUnit3" Version="4.8.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="nunit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.11.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
</ItemGroup>
</Project>
public class Tests
{
[Test, SmartAutoData(typeof(Tests), nameof(Test1Configuration))]
public void Test1(string test)
{
Assert.That(test, Is.EqualTo("Hello World"));
}
static void Test1Configuration(IFixture fixture)
{
fixture.Register(() => "Hello World");
}
[Test, SmartAutoData]
public void Test2(string test)
{
Assert.That(test, Is.Not.EqualTo("Hello World"));
Assert.That(test, Is.Not.EqualTo("Foo Bar"));
}
[Test, SmartAutoData(typeof(Tests), nameof(Test3Configuration))]
public void Test3(string test)
{
Assert.That(test, Is.EqualTo("Foo Bar"));
}
static void Test3Configuration(IFixture fixture)
{
fixture.Register(() => "Foo Bar");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment