0

I'm trying to setup Unit tests for this. But every example I've seen that actually works is this type of setup. It will work this way.

//Setup DBContext
public MyContext(DbConnection connection) : base(connection, true){}
//Have some service that gets passed the context etc..
public class SomeService()
{
  public SomeService(MyContext passedContext){
      Context = passedContext;
  }
  public MyContext Context {get;set;}

  public Book GetBook(int id){
     return Context.Books.Find(id);
  }
}

But the way I have mine setup is something like this, And I can't figure out how to do it correctly without breaking everything

public class SomeService()
{
    public async Task<Book> GetBook(int id){
      using(var context = new MyContext()
      {
       return await context.FindAsync(id);
      }
   }
 }

So how can I test this out, without having a Context Property and passing the context around. Because from what I've read I cant do it async, because DBContext isn't thread safe. But I also cant test it with Effort unless I pass everything the correct context from Effort..

Wont work because I use a using on every service method.

Dylan
  • 1,068
  • 12
  • 25
  • 1
    Abstract the context so that it can be replaced/mocked when testing. right now the db context is too tightly coupled to allow for test-ability – Nkosi Feb 23 '17 at 15:45
  • How would I do that, while being able to use async? The first way I showed allows me to test because it decouples the Dbcontext, but also makes me change all my service calls to the DB from async. – Dylan Feb 23 '17 at 15:47

1 Answers1

0

Asyns is not a problem here. Please refer to this question to see how implement factory method: What happens to using statement when I move to dependency injection

Community
  • 1
  • 1
komsky
  • 1,568
  • 15
  • 22
  • So I need to wrap the dbcontext in a factory? – Dylan Feb 23 '17 at 16:32
  • Yes, exactly. You want this to be testable in isolation, right? Unless you are trying to achieve something I didn't understand. – komsky Feb 24 '17 at 20:46
  • From what I've read (http://mehdi.me/ambient-dbcontext-in-ef6/) this way is basically the injected dbcontext, which apparently doesn't work well with threading either? I can't figure out a good way around this.. – Dylan Feb 24 '17 at 21:29
  • Dylan, have you read to the end this article or just copied first code example (what actyally author uses as bad code)? There is exactly example of injection of DbContext with factory. Rule of thumb: using 'new' keyword is a code smell. – komsky Feb 26 '17 at 16:46
  • I've read it multiple times. He then says it's almost impossible to use the injection method while async – Dylan Feb 26 '17 at 17:57