Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test persistence?

As a novice in practicing test-driven development, I often end up in a quandary as to how to unit test persistence to a database.

I know that technically this would be an integration test (not a unit test), but I want to find out the best strategies for the following:

  1. Testing queries.
  2. Testing inserts. How do I know that the insert that has gone wrong if it fails? I can test it by inserting and then querying, but how can I know that the query wasn't wrong?
  3. Testing updates and deletes -- same as testing inserts

What are the best practices for doing these?


Regarding testing SQL: I am aware that this could be done, but if I use an O/R Mapper like NHibernate, it attaches some naming warts in the aliases used for the output queries, and as that is somewhat unpredictable I'm not sure I could test for that.

Should I just, abandon everything and simply trust NHibernate? I'm not sure that's prudent.

like image 407
Jon Limjap Avatar asked Aug 05 '08 09:08

Jon Limjap


People also ask

How do you test data persistence?

One way to test a persistence layer is to write tests that run against the database. For example, we can write tests that create and update persistent objects and call repository methods.

What is a persistence test?

Persistence tests help keep your user's data safe. Statefulness can make persistence tests difficult to write. You can use an in-memory database to help handle stateful tests. You need to include both set up ( @Before ) and tear down ( @After ) with persistence tests.

How long should a unit test last?

Typical time budgeted on writing unit tests is about 1 day for every feature that takes 3-4 days of heads down coding. But that can vary with a lot of factors. 99% code coverage is great. Unit tests are great.


2 Answers

Look into DB Unit. It is a Java library, but there must be a C# equivalent. It lets you prepare the database with a set of data so that you know what is in the database, then you can interface with DB Unit to see what is in the database. It can run against many database systems, so you can use your actual database setup, or use something else, like HSQL in Java (a Java database implementation with an in memory option).

If you want to test that your code is using the database properly (which you most likely should be doing), then this is the way to go to isolate each test and ensure the database has expected data prepared.

like image 104
Mike Stone Avatar answered Oct 09 '22 09:10

Mike Stone


As Mike Stone said, DbUnit is great for getting the database into a known state before running your tests. When your tests are finished, DbUnit can put the database back into the state it was in before you ran the tests.

DbUnit (Java)

DbUnit.NET

like image 38
Josh Brown Avatar answered Oct 09 '22 07:10

Josh Brown