Created
November 27, 2017 08:51
-
-
Save dgg/adfb41424a50698acd999d64c9447ee9 to your computer and use it in GitHub Desktop.
Testing DSLs
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
int even = 2, odd = 3; | |
// meh | |
Assert.That(even % 2, Is.EqualTo(0)); | |
// slightly better (message) | |
Assert.That(odd % 2, Is.Not.EqualTo(0), "Number must be odd"); | |
// better | |
Assert.That(odd, new EvenContraint()); | |
// best | |
Assert.That(even, Must.Be.Even()); | |
//////////////////////////////////////// | |
public class EvenContraint : NUnit.Framework.Constraints.Constraint | |
{ | |
public override string Description => "an even number"; | |
public override ConstraintResult ApplyTo<TActual>(TActual actual) | |
{ | |
return new Result(this, actual, isEven(Convert.ToInt32(actual))); | |
} | |
private static bool isEven(int number) | |
{ | |
bool even = number % 2 == 0; | |
return even; | |
} | |
class Result : ConstraintResult | |
{ | |
private readonly object _actual; | |
public Result(NUnit.Framework.Constraints.IConstraint constraint, object actual, bool success) : | |
base(constraint, actual, success) | |
{ | |
_actual = actual; | |
} | |
public override void WriteActualValueTo(MessageWriter writer) | |
{ | |
writer.Write("odd ("); | |
writer.WriteValue(_actual); | |
writer.Write(")"); | |
} | |
} | |
} | |
// using Testing.Commons for Must entry points | |
public static class MustExtensions | |
{ | |
public static EvenContraint Even(this Must.BeEntryPoint entry) | |
{ | |
return new EvenContraint(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment