How do YOU unit test data access code?

I see fairly regular, very academic, debates about what exactly you should unit test.

So how do you test data access code? It seems pretty typical these days to write a class that inherits some abstract class and does all the actual data store touching, so how do you test that code?

I do it a particular way, sure, but I would rather ask about the typical practice instead of looking silly. ;)


  • I test this against an access database - there is a master in source control, and the test works against a copy.

    Works fine for most things. When I need to operate against SQL Server, I test against a database and modify my code to rollback instead of commit :-)

  • Daniel, I would say that when your working with a substantial amount of data this 'very small' performance penalty soon mounts up.

    One of the major points of Unit Testing is Regression testing to ensure that as changes are made the underlying system functions still remain constant and work as required by the business logic.

    The Unit Test column check is in place to ensure that if the data structure is altered and no longer works with the function the test will fail and will indicate that the current changes have caused the working build to fail.

    If you really wanted to you could use:

    dr.GetString(dr.GetOrdinal(“mycol”)) to get the column ordinal and then use this.

    You could also map the ordinals once and re-use them which would be pretty good.

    Imagine a int32 the way you suggest:

    int i = Convert.ToInt32(dr["myCol"])

    This is well known to be less effecient than int i = dr.GetInt32(0).

    It all boils down to how much you care about the performance of your system, me personally I try to use best practice and prefer the code to run with performance in mind than readability.

  • See my MSDN article dealing with exactly these issues: how do you test your data access layer?

  • Roy, had a read of the article not sure where it directly address's the problems of say for example: Reading data from the database and testing the returned data against the expected result.

  • If your SELECT is calling out each column, using the ordinals is fine, and it's what I do on everything now.

Comments have been disabled for this content.