Stubbing Data for Unit Testing

Unit tests should not have an external dependency on a database, but unit tests need data. To help with this, Database Abstraction has a StubDataReader class which can return one or more StubResultSets. This part of the code was adapted from the Subtext blog project, as described by Phil Haack.

A StubResultSet is constructed with strings that will be used as the column names for the data. Once the result set is created, use the AddRow() method to fill it with data. (This step is optional; skip it for a "no results found" scenario.) AddRow() will throw an exception if the number of values it receives is not equal to the number of columns given in the constructor. Also, to pass a null, use DBNull.Value instead of a simple null; this is the proper way to simulate a null column.

Once the result set(s) have been created, pass them to a StubDataReader. A StubDataReader is not required to have result sets; if you are not testing a Select method, you can construct it without them.

namespace DocExample.Tests
{
    using DatabaseAbstraction.Utils.Test;
    using DocExample.Services;

    /// <summary>
    /// Unit Tests for the ExampleService
    /// </summary>
    [TestClass]
    public class ExampleServiceTest
    {
        /// <summary>
        /// Set up data for a unit test
        /// </summary>
        [TestMethod]
        public void SetUpData()
        {
            var dataOne = new StubResultSet("col1", "col2", "colN");
            dataOne.AddRow(14, "abc", new DateTime(2012, 4, 22));

            var dataTwo = new StubResultSet("col3", "col4", "colNagain");
            dataTwo.AddRow(15, "def", new DateTime(2012, 6, 18));

            var reader = new StubDataReader(dataOne, dataTwo);
        }
    }
}

Now that we have data, we can do something with it (in our next example).

<<

Last edited Apr 1, 2013 at 6:30 PM by danielsummers, version 2

Comments

No comments yet.