Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Last active December 11, 2015 03:28
Show Gist options
  • Save akimboyko/4538235 to your computer and use it in GitHub Desktop.
Save akimboyko/4538235 to your computer and use it in GitHub Desktop.
Build constraints inside a single test suing NUnit.Framework.Constraints.Constraint
void Main()
{
// nunit runner
NUnit.ConsoleRunner.Runner.Main(new string[]
{
Assembly.GetExecutingAssembly().Location,
});
}
public class ClassUnderTest
{
public string First { get; set; }
public string Second { get; set; }
public string Third { get; set; }
}
[TestFixture]
public class Tests
{
public IEnumerable TestCasesSourcesSeparateProperties
{
get
{
yield return new TestCaseData("First", "foo").SetDescription("Test Property 'First'");
yield return new TestCaseData("Second", "bar").SetDescription("Test Property 'Second'");;
yield return new TestCaseData("Third", "boo").SetDescription("Test Property 'Third'");;
}
}
[TestCaseSource("TestCasesSourcesSeparateProperties")]
public void ClassUnderTest_CheckProperty_ExpectValue(string propertyName, string expectedPropertyValue)
{
// Arrange
ClassUnderTest cut = null;
// Act: perform actual test
cut = new ClassUnderTest { First = "foo", Second = "bar", Third = "boo" };
// Assert
Assert.That(cut, Is.Not.Null
.And.Property(propertyName).EqualTo(expectedPropertyValue));
}
public IEnumerable TestCasesSourcesAllProperties
{
get
{
yield return new TestCaseData(
new Tuple<string, string>[] {
Tuple.Create("First", "foo"),
Tuple.Create("Second", "bar"),
Tuple.Create("Third", "boo") } as object)
.SetDescription("Test all properties using Constraint expression");
}
}
// get test parameters from TestCasesSourcesAllProperties
[TestCaseSource("TestCasesSourcesAllProperties")]
public void ClassUnderTest_CheckAllProperty_ExpectValues(Tuple<string, string>[] propertiesNamesWithValues)
{
// Arrange
ClassUnderTest cut = null;
// Act: perform actual test, here is only assignment
cut = new ClassUnderTest { First = "foo", Second = "bar", Third = "boo" };
// Assert
// check that class-under-test is not null
NUnit.Framework.Constraints.Constraint expression = Is.Not.Null;
foreach(var property in propertiesNamesWithValues)
{
// add constraint for every property one by one
expression = expression.And.Property(property.Item1).EqualTo(property.Item2);
}
Assert.That(cut, expression);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment