Do Da Unit Testing Database

When working with temporal data stored in an RDBMS it can be tricky to do proper unit testing (actually it's nearly impossible). Essentially, to be able to re-run unit tests you need to be able to restore time and space like it was the previous run. A technique I found usefull was explicitly setting the system time before starting the actual test (PInvoking a Win32 API). After the test had run, I'd just sync up with the domain controller using net time. Ofcourse, it's never going to be 100% the same, but for most non-real-time systems this will do.

A common problem when doing unit testing is restoring a database(SQL2K) reliably to a known state. The good news is that it's quiet simple (and compared to database recreation via scripts, very fast)!

  • Make sure your database has it's AUTO_CLOSE option set. Detach it and remember where that .mdf is located!
  • The connection string used by your DAL or ObjRelMapper should look like: "Data Source=(local);Initial Catalog=MyDataBase;AttachDBFilename=D:\MyDataBase.mdf;Pooling=false;Integrated Security=true;"
    • AttachDBFilename points to the detached database(a copy would even be better).
    • Pooling=false ensures you will be able to detach the database later on (should we want to) and that you can re-run the unit tests without exiting the test environment.
  • If you want to detach your database, use a connection string which connects to the master database and do an sp_detach_db of your test database. This will allow you to move the .mdf around.

 

Published 02 March 2004 11:41 PM by yreynhout

Comments

# Roy Osherove said on 21 July, 2004 02:08 AM
Sounds good, but wouldn't the database still be holding the data from the unit tests after the run? would detaching it roll it back to a known state or do I detach it and attach a fresh copy of the original every time?
# Yves Reynhout said on 21 July, 2004 06:01 AM
Attach a fresh copy of the original every time (implied by "restoring a database(SQL2K) reliably to a known state").

Leave a Comment

(required) 
(required) 
(optional)
(required)