Write your own NUnit constraint (in VB) - Part 1
NUnit constraints offer a different style to crafting your unit tests, rather than write.
Assert.IsEqual(expected,actual)
you could write
Assert.That(expected, Is.EqualTo(actual))
Or in VB as Is is a reserved keyword - Assert.That(expected, [Is].EqualTo(actual))
'Is' is one of the syntax helpers within NUnit.Framework.SyntaxHelpers to add a little syntax sugar, the above could be written as
Assert,That(expected, new EqualConstraint(actual))
Where EqualConstraint lives in NUnit.Framework.Constraints but the syntax sugar is so much nicer.
The That assert takes a IConstraint interface and if you want to craft your own constraints you can do so by using NUnit's own Constraint class. For our own purposes let's create a custom constraint that tests the cast of null (nothing) to a datetime value.
1: Imports NUnit.Framework
2: Imports NUnit.Framework.Constraints
3:
4: Public Class DateFormatConstraint
5: Inherits Constraint
6:
7: Private testDate As Date
8:
9: Public Sub New()
10: Me.testDate = CType(Nothing, Date)
11: End Sub
12:
13: Public Overrides Function Matches(ByVal actual As Object) As Boolean
14: If (CType(actual, Date) = CType(Nothing, Date)) Then
15: Return True
16: Else
17: Return False
18: End If
19: End Function
20:
21: Public Overrides Sub WriteDescriptionTo(ByVal writer As MessageWriter)
22: writer.WritePredicate("Date is not null") 23: writer.WriteExpectedValue(Me.testDate)
24: End Sub
25:
26: End Class
27:
Note that the new constraint class overrides the base class Matches and WriteDescription methods with our own requirements.
We can now use this as follows
Assert.That(expected, New DateFormatConstraint())
Getting this new constraint inside of Is syntax helper can be done and will be covered in part 2......