views:

44

answers:

2

I have service classes based on Entity Framework 4. I'd like to test them on a database filled with pre-generated sample data. The problem is: I would like the tests, whether passed or failed, to not actually touch the database, so that it may be re-used for other tests.

Thus I'd like ObjectContext.SaveChanges to pretend that everything's fine, and keep the changes in memory, but silently omit their actual persistence in the data source. Is this possible?

P.S. I am aware of the repository pattern, but would not like to use it in this case.

A: 

I am going to go out on a limb here with this one... I know that it works with linq-to-sql

You can override the savechanges method in your context/container

and actually remove the base.SaveChanges();

It looks like this:

public override int SaveChanges(SaveOptions options){
   return base.SaveChanges();
}

so if you uncomment this line, you can adapt it to your situation

sTodorov
Thanks, will try this. (Or maybe just follow the route mentioned above...)
Vasiliy Faronov
Commenting or uncommenting a line for unit tests seems like a terrible idea to me... what if you forget to uncomment the call to `base.SaveChanges` before you go to production ? You should *never* modify the code you're testing just for the purpose of testing. A better idea would be to create a specific ObjectContext for tests, where you would override `SaveChanges`. But even that is not a good solution, because changes made to the `ObjectContext` are not visible in queries until you call `SaveChanges`
Thomas Levesque
A: 

You just need to wrap your tests in a transaction that you don't commit :

using(var context = new MyObjectContext())
{
    context.Connection.Open();
    using (var transaction = context.Connection.BeginTransaction())
    {
        // Your tests here
        ...

    } // At this point, the transaction is rolled back, since it hasn't been commited
}
Thomas Levesque