views:

248

answers:

1

In NHibernate, there is a method doing something like ThisOrThat.VeryfyMappings() (I don't know the exact definition of it since it was a while ago I last tried NHibernate...)

I recall seeing a blog post somewhere where the author showed how to do some similar testing in Entity Framework 4, but now I cant find it. So, how do I test my EF4 Code-Only mappings?

A: 

You should be able to apply the same approach as described in this blog post. It describes how to do this for Fluent NHibernate, but it should be pretty much the same for EF4.

You'll need to implement the Validate(The)Mappings method yourself, and regardless of whether you use the repository approach or go directly through the context the basic idea is the same: insert an object and retrieve it using a second repository/context to verify that all fields have been correctly transferred. Additional checks will be needed to verify references.

Morten Mertner
Well, implementing this `VerifyTheMappings` method is then what I need help with. What does the method need to do? And how do I ensure that it actually tests what I want it to test?
Tomas Lycken
Your mappings describe how classes map to underlying database tables, so by exercising that mapping using a read and write operation you essentially verify that it works. The verification requires an actual database and the read/write operations will be the insert and selects mentioned in the answer.It's really not that complicated. 1) Define mappings. 2) Create VerifyMappings method and write code to insert object followed by code to retrieve the saved object (using a different context to bypass any caching). 3) Create unit test to invoke VerifyMappings.
Morten Mertner
OK. So basically, I just write a method that uses all mappings I have, inserts an object of the given type with all the parameters specified using one ObjectContext, retrieves the same object using a different ObjectContext instance, and verify that all the properties have the same values?
Tomas Lycken
That's exactly right. You might also want to test relations by creating tests where you work with more than one object at a time. You'd follow the same basic approach, but rather than testing member properties you test that the navigation/links between objects are preserved correctly. It would also be a good idea to run each test in a separate transaction that is rolled back automatically, as this leaves the database in a known (unmodified) state after each test. Your unit test framework provides attributes that easily lets you accomplish this (e.g. SetUp and TearDown in NUnit).
Morten Mertner