Testing code that depends on a database

I often get asked questions about how to test code that relies heavily on a database. People often assume that because an application relies on a database that the test must also rely on a database. Then they get snagged up in all the problems with testing against databases such as not messing up the data for other people and being able to setup the data so that the test can expect a certain result when the Company table is queried for companid 1357, or even which company should be queried for?

“I need a Company record that has more than 500 employees and is publicly traded to test this bit of logic I wrote. Which companyid should I use? Is the data going to change? Should I just create a new test company in the database? I hope nobody touches it.”

My short answer is: Don’t include the database when you’re testing your business logic (unless you are testing business logic that’s in the database, but that’s a whole seperate topic that won’t be covered here).

How do you do that?

  1. Seperate the code that accesses the database from your business logic implementation.
  2. Create a well-defined interface for that data access object. Like ICompanyDataAccess.
  3. Test the business logic by plugging a Mock object in to replace the database implementation of the data access object.

For further reading, refer to this excellent blog post on mock testing with NMock:  http://msdn.microsoft.com/msdnmag/issues/04/10/NMock/

Comments, questions, or experiences relating to mock testing or seperating business logic from data access? Please comment below.

Watir assisted manual testing results

Okay, that was easy!

I have three separate Watir scripts written to open IE and:

  1. Automatically login with a valid test username and password
  2. Login with a valid username and invalid password
  3. Login with a non-existent username

Manually each of these procedures take about 25 seconds. Running these using Watir from my ruby editor takes about 5 seconds. That’s 5 times faster!!!

If I estimate that I need to log into that app 100 times today to do my manual testing, I’ll be spending 8 minutes logging in rather than  42 minutes. I’m already going to save aproximately 2,000 seconds or 33 minutes of wasted time (it took less than 5 minutes to write the scripts). Multiply that by 10 developers and that’s a savings of over 5 hours per day! That could be another feature.