Mark Gilbert's Blog

Science and technology, served light and fluffy.

Unit testing with DBNull

Recently, I was writing a class that would parse a DataRow (returned by a stored procedure) and construct a strongly-typed object from it.  I wanted to test the case where the stored procedure returned DBNull for one of the fields.  My first attempt at the unit test setup started out like this:

Dim DPTable As DataTable
Dim DataRowValues() As Object = {Value1, Value2, Value3, System.DBNull.Value, Value4}

DPTable = New DataTable
DPTable.Columns.Add(New DataColumn(“Col1Name”, GetType(Long))
DPTable.Columns.Add(New DataColumn(“Col2Name”, GetType(String))
DPTable.Columns.Add(New DataColumn(“Col3Name”, GetType(Long))
DPTable.Columns.Add(New DataColumn(“Col4Name”, GetType(String))
DPTable.Columns.Add(New DataColumn(“Col5Name”, GetType(String))

DPTable.Rows.Add(DataRowValues)
MyTestObject = New MyClass(DPTable.Rows(0))

Mock up a table and add a test row to it.  Simple.  The problem was the compiler complained about trying to directly assign System.DBNull.Value in the Object() array: "Value of type ‘System.DBNull’ cannot be converted to ‘String’." 

Ok, so DBNull isn’t a value you can assign to a .NET object. What you CAN do, however, is use a valid value in the Object() array and then assign DBNull to that cell in the DataRow, but after you’ve added it to the DataTable:

Dim DataRowValues() As Object = {Value1, Value2, Value3, SomeValidValue, Value4}

DPTable.Rows.Add(DataRowValues)
DPTable.Rows(0).Item(“Col4Name”) = System.DBNull.Value
MyTestObject = New MyClass(DPTable.Rows(0))

That worked like a charm.

Advertisements

October 13, 2009 - Posted by | Agile, Visual Studio/.NET

Sorry, the comment form is closed at this time.

%d bloggers like this: