简体   繁体   中英

Unit Test with Effort EF6 with Async Methods

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM