0

Suppose that I have the following code:

public Item CoolFunction(int i) {
    var result = SomeContext.Item.First(t => t.Id == i);
    return result;
}

Suppose for whatever reason I want to unit test this method. In this case, I can use MS Fakes to fake the context. But if I want to test this code against a real Db, I have to write another unit test to do so. Is there a (nice or convenient or recommended) way to write one unit test with a switch that can test with the fake context or real db?

Husain
  • 784
  • 1
  • 9
  • 22
  • 2
    If you use dependency injection you can setup the IoC container to inject any context instance. – Gert Arnold Mar 09 '16 at 20:48
  • @GertArnold I don't think that will be an easy task, specially that faking a database will require a lot of preparation. Do you know of anyone who did that elegantly online somewhere? – Husain Mar 10 '16 at 03:44
  • [I've never been optimistic about mocking EF](http://stackoverflow.com/a/13352779/861716). But maintaining a database for integration tests also requires careful preparation (although I think it's easier than composing a mock "universe"). Introducing IoC if you don't use it yet is serious work. It may be worth the effort though. – Gert Arnold Mar 10 '16 at 08:01

1 Answers1

1

I definitely recommend checking out Effort: https://effort.codeplex.com/

It's an "Entity Framework Unit Testing Tool" that sets up an in-memory database. The database can either be "transient" (recreated for each test) or "persistent" (the same database is maintained for all unit tests).

The best of both worlds for unit and integration testing. I've found it to be simpler than just mocking the IDbSet.

RJB
  • 2,063
  • 5
  • 29
  • 34
  • That is a great tool. The only problem is that I can't rely on that code which "poorly" maintained to write code that will last years. But thank you for this important note. It could have been the perfect solution to my problem. – Husain Mar 10 '16 at 03:46