views:

53

answers:

2

Hello,

I keep reading a lot of opinions in favor of Unit Testing, which is a procedure I have not been following so far and have a few questions.

As I understand it, the basics of Unit Testing is to run some procedures in your code, and compare the returned value against the expected value, and see if it matches to determine whether a test has passed or not.

In the simple examples that I've seen, it is reasonably easy as they were just tests testing integer or decimal output values, which are fairly straightforward to test indeed, as everything happens more or less in memory.

Now, let's imagine that I have a procedure which writes to a file, or inserts records in a SQL Server database... whenever I'll run my tests, I would have those writes happen in either my file or my server, and if I run the test several times, I may run into issues... like primary keys violations if the records have already been inserted in a previous test.

I understand that the tests should be done on a test server, but even then, a lot of the tests seem to cause unpractical maintenance such as restoring a database everytime you want to run a test is going to be frustrating and time consuming in the long run.

In short, I'm curious to know how do the regular unit testing developers manage this kind of tests, modifying the state of the environment, in a easy, time and cost efficient and straightforward manner?

Thanks.

I'm primarily coding in C# and using VS 2008, but I guess that's a fairly generic question

+4  A: 

You need to looking into Mocking frameworks.

These allow you to set up tests as though you were writing to the database, but you don't actually make any changes at all. You're testing your code not the database connection so as long as the mock object returns values as if it were the real code your test is valid.

You can set up the mock object to test both valid and invalid cases, and you can even simulate losing the database connection (for example).

ChrisF
Thanks, any suggestion for good and easy ones, that do not take too long to learn?
Kharlos Dominguez
@Kharlos Dominguez: if you're familiar with lambda expressions, Moq is very simple, it's a single dll you make your test project reference and then add your using, and here's the quickstart which outlines it's usage: http://code.google.com/p/moq/wiki/QuickStart
Jimmy Hoffa
+3  A: 

Unit testing refers to testing code in isolation, the tests you're referring to are integration tests or build verification tests.

When writing unit tests for pieces of code that use databases or streams, you use mocking frameworks usually (moq is the one I always suggest) or any of a variety of techniques which focus on testing the code in isolation.

Jimmy Hoffa