Oftentimes, I have a need to parse the data in a data row or
table, to ensure that certain known data exists within it. That way I can be
sure that the returned result set is correct. Because of this, a custom
assertion can be a parent static class that reuses the regular assertions of
the NUnit framework, while providing additional capabilities, such as strong
typing.
This assert class is a static class that exposes a series of
methods. Most of the NUnit classes have three sets of methods for a single type
of assert.
Listing 2
public static void ColumnIsNotNull(DataTable table, string columnName) { }
public static void ColumnIsNotNull(DataTable table, string columnName,
string message) { }
public static void ColumnIsNotNull(DataTable table, string columnName,
string message, params object[] parameters) { }
When determining if a column is not null, the first method
defines the base assertion criteria and the last two allow a personalized
message. The assertion classes use a constraint class that implements the
IConstraint interface or the Constraint base class. Any constraints, including
custom constraints, can be used as such and the constraint works well with the
Assert.That method.
Listing 3
Assert.That(table, new DataTableNullConstraint(columnName, notNull),
message, parameters);
DataTableNullConstraint is a custom constraint used to
determine whether the expected criteria meet the actual. In some cases the
expected and actual values are blatantly clear, such as with Assert.AreEqual.
It contains two values of a specified type that can be compared. In some cases,
these are not blatant, such as the Assert.IsNotNull method, as the expected and
actual requirements depend on the null status of an object.
With this custom contraint, any expected criteria are passed
through the constructor or factory method of the constraint. The actual is
passed through one of the abstract methods, called Matches. The Matches method
returns a boolean value for whether the expected value matches the actual
(which is passed into the method).
In addition to Matches, the WriteDescriptionTo method is
also abstract and used to write the error information to the screen. The
MessageWriter object has multiple write methods, such as WriteExpected and
WriteActual to write the expected/actual values. The WriteMessageLine method
writes a descriptive message about the problem, the WriteValue method writes a
value to the string, and there are other methods available as well.