How to Make ORM-Bound Code Testable

ormtddunit testing

In Test Driven Development, how do I make code bound to an ORM testable?

I am using a Micro-ORM (PetaPoco) and I have several methods that interact with the database like:

AddCustomer

UpdateRecord

etc.

I want to know how to write a test for these methods. I searched YouTube for videos on writing a test for DAL, but I didn't find any.

I want to know which method or class is testable and how to write a test before writing the code itself.

Best Answer

Unit testing the code relying on your DAL should be straight-forward: use the repository pattern to decouple your business layer from your ORM. Provide your POCOs by an abstract repository, then you can either provide a "real" repository in production (which uses your ORM), or a mock repository for testing purposes which delivers just test-data POCOs without any DB access. Using an ORM which works with POCOs here has the advantage that you can easily create that objects in memory, without the need to rely on the ORM.

A different question is how to automatically test methods like "AddCustomer", assumed that this method contains only database or ORM related code. Having a short look into the PetaPoco documentation and source code, it seems to support just one database with in-memory capabilities: SqlLite. So I guess you could set up a lightweight SqlLite instance for your testdata and write your tests against this.

Theoretically, you could do this also with a full-blown relational DB system like Oracle or MS SQL server, but that option is often too slow and needs too much administrative overhead to be practical. If you want trying this route anyway, I suggest you have a look at DBUnit.NET, which supports this approach.

Whatever you will do, it may be a good idea to separate those two cases in your code: write (1) code pulling the needed objects from your DB into memory, and (2) separate code for doing the business logic, without any DB access. Surely you will need (3) code that manages (1) and (2)to make them work together, but (1) and (2) could be tested then more easily in isolation.

Related Topic