Created
March 25, 2018 15:51
-
-
Save Kralizek/50c82058902347da12ea1ac787cde096 to your computer and use it in GitHub Desktop.
AutoValueAttribute for AutoFixture/NUnit
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
[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; | |
} | |
} |
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
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