c# - How to moq Entity Framework SaveChangesAsync? -


mock<idbcontext> dbcontext;  [testfixturesetup] public void setupdbcontext() {     dbcontext = new mock<idbcontext>();     dbcontext.setup(c => c.savechanges()).verifiable();     dbcontext.setup(c => c.savechangesasync()).verifiable();     dbcontext.setup(c => c.customers.add(it.isany<customer>()))              .returns(it.isany<customer>()).verifiable(); }  [test] public async task addcustomerasync() {     //arrange     var repository = new entityframeworkrepository(dbcontext.object);     var customer = new customer() { firstname = "larry", lastname = "hughes" };      //act     await repository.addcustomerasync(customer);      //assert     dbcontext.verify(c => c.customers.add(it.isany<customer>()));     dbcontext.verify(c => c.savechangesasync()); }  [test] public void addcustomer() {     //arrange     var repository = new entityframeworkrepository(dbcontext.object);     var customer = new customer() { firstname = "larry", lastname = "hughes" };      //act     repository.addcustomer(customer);      //assert     dbcontext.verify(c => c.customers.add(it.isany<customer>()));     dbcontext.verify(c => c.savechanges()); } 

and here's want test:

public class entityframeworkrepository {     private readonly idbcontext dbcontext;      public entityframeworkrepository(idbcontext context)     {         dbcontext = context;     }      public async task addcustomerasync(customer customer)     {         dbcontext.customers.add(customer);         await dbcontext.savechangesasync();     }      public void addcustomer(customer customer)     {         dbcontext.customers.add(customer);         dbcontext.savechanges();     } } 

addcustomers test passes.

addcustomersasync test fails, keep getting nullreferenceexception after calling await dbcontext.savechangesasync().

at masonogcrm.dataaccess.ef.entityframeworkrepository.d__2.movenext() in c:\users\mason\desktop\repositories\masonogcrm\src\dataaccess.efrepository\entityframeworkrepository.cs:line 43

i can't see that's null in code. dbcontext not null. equivalent test of addcustomers identical exception of not being async runs expected. suspect haven't performed correct setup of savechangesasync in setupdbcontext() don't know fix it.

you right problem occurs because 1 of setups incorrect :: dbcontext.setup(c => c.savechangesasync()).verifiable();.

the method return task , forgot return task therefore null returns.

you can remove dbcontext.setup(c => c.savechangesasync()).verifiable(); or change setup like:

dbcontext.setup(c => c.savechangesasync()).returns(() => task.run(() =>{})).verifiable(); 

Comments