0

I would like to create unit tests for data dependent code. For example:

A user class that has the usual create, update & delete.

If I wanted to create a test for "user already exists" scenario, or and update or delete test. I would need to know that a specific user already exists in my database.

In such cases, what would be the best approach to have stand alone tests for these operations that can run in any order?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Matthew Grima
  • 1,513
  • 5
  • 25
  • 40
  • Related, and possible duplicate: http://stackoverflow.com/questions/145131/whats-the-best-strategy-for-unit-testing-database-driven-applications – John Saunders Aug 16 '14 at 20:31

1 Answers1

6

When you have dependencies like this think about whether you want to be Integration Testing as opposed to Unit Testing. If you do want to do Unit tests take a look at using Mock Data.

Integration Testing: Tests how you code integrates with different parts of a system. This can be making sure your code connects to a database properly or has created a file on the filesystem. These tests are usually very straight-forward and do not have the same constraint of "being able to run in any order." However, they require a specific configuration in order to pass which means they do float well from developer to developer.

Unit Testing: Tests your code's ability to preform a function. For example "Does my function AddTwoNumbers(int one, int two) actually add two numbers?" Unit tests are to ensure any changes in code does not effect the expected results.

When getting into areas like "Does my code call the database any enter the result correctly?" you need to consider that unit tests are not meant to interact with the system. This is where we get into using "mock data." Mock classes and mock data take the place of an actual system to just ensure that your code "called out in the way we were expecting." The difficult part about this is it can be done but most of the .Net Framework classes do not provide the needed Interfaces in order to do it easily.

See the MSDN page on Tesing for more info. Also, consider this MSDN article on Mock Data.

alstonp
  • 700
  • 6
  • 25