Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I unit-test a simple CRUD-class?

I am right now trying to do very, very simple stuff with unit-testing in VS2008, to get started and get a feel for this. I think I have testing of small non-database stuff down, but now I want to start testing my real solutions - that are almost always CRUD-heavy.

So let's assume I have a class in the data-access layer, that does standard CRUD-stuff for a Product. I want a test for each of the methods on the Product.

Below is what I could think up without any real knowledge on the subject. Is this the way to do it, or... How should I approach this? Cool (but simple, please) references are also very welcome.

Create

  1. Feed some relevant parameters (Product name etc)
  2. Check that an identity is returned.
  3. Delete the Product (to clean up).

Read

  1. Create a new product
  2. Invoke the select-method
  3. Make sure the product-name matches the one I gave it on creation
  4. Delete the produkt

Update

  1. Create a new Product
  2. Update some fields on it
  3. Select the product
  4. Verify some fields match
  5. Delete hte product

Delete

  1. Create a new Product, keep the ProductID
  2. Delete the product (Cleanup on aisle 4!)
  3. Check if the product with this Productid is still in the table?

EDIT:

...Or should I simply create a single test, that tests all of these things?

like image 980
Kjensen Avatar asked Apr 17 '09 17:04

Kjensen


1 Answers

I have been down this road and here are all of the problems you are going to run into:

1) This looks good for one record, but what happens when you need 4 other records to create that record? You end up creating 4 records to test inserting your one record. This causes all of the following issues.

2) Creating and deleting 4-5 records per test is slow, it will slowly add up and running your tests will take 45 minutes (trust me I was there). Slow tests mean you will never run them, which means they will be broken most of the time and useless.

3) Your delete will fail for some missed foreign key relation or dependency and then trash data will be left in your database. This trash data will then cause other tests to fail.

In light of this I would implore you to consider two things. The first is to try out using an ORM instead of writing all this logic yourself. Then you only need to test your mapping files (or even less depending on the ORM you use) or look into mocking so you can isolate the logic in your data access code from directly accessing the database.

like image 161
James Avery Avatar answered Sep 29 '22 21:09

James Avery