Skip to content

Instantly share code, notes, and snippets.

@Kralizek
Created March 25, 2018 15:51
Show Gist options
  • Save Kralizek/50c82058902347da12ea1ac787cde096 to your computer and use it in GitHub Desktop.
Save Kralizek/50c82058902347da12ea1ac787cde096 to your computer and use it in GitHub Desktop.
AutoValueAttribute for AutoFixture/NUnit
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class AutoValueAttribute : DataAttribute, IParameterDataSource
{
private readonly Lazy<IFixture> _fixtureLazy;
private IFixture Fixture => _fixtureLazy.Value;
public AutoValueAttribute() : this (() => new Fixture())
{
}
public AutoValueAttribute(Func<IFixture> fixtureBuilder)
{
if (fixtureBuilder == null)
{
throw new ArgumentNullException(nameof(fixtureBuilder));
}
_fixtureLazy = new Lazy<IFixture>(fixtureBuilder, LazyThreadSafetyMode.PublicationOnly);
}
public IEnumerable GetData(IParameterInfo parameter)
{
var context = new SpecimenContext(Fixture);
var obj = context.Resolve(parameter.ParameterType);
yield return obj;
}
}
public class AutoValueAttributeTests
{
[Test]
public void AutoValueAttribute_should_provide_a_fixed_Model(
[Values] bool flag,
[Range(1,5)] int statusCode,
[AutoValue] Model model
)
{
Assert.That(model, Is.Not.Null);
}
}
public class Model
{
public int Value { get; set; }
public string Text { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment