Another discussion on the EF core Memory Database Unit test problem

Source: Internet
Author: User
Tags assert

(This article also published in my public number "dotnet daily Essence article", Welcome to the right QR code to pay attention to. )

Preface: What if you encounter an "unreachable object" error while using EF Core's in-memory database for unit testing?

The previous tips for using include in EF Core 1.0 briefly talked about how to use the EF Core Memory database for unit testing. However, there is a small problem with this approach, which is that it is easy to "fail to access the freed objects" error.

In the previous sample code (HTTP://GIT.OSCHINA.NET/IKE/CODES/JTU9DNSK3PE6X24CLBQ50), the unit test passed smoothly, is because the DB and DB2 two instance objects are not placed in the using inside to let them disposed out automatically. In most cases, the correct wording should be the use of using, even if the use is not used, if the one-time execution of multiple tests, then you will encounter this "cannot access the disposed object" error.

According to the discussion here (https://github.com/aspnet/EntityFramework/issues/4092), the root cause of this error is that EF Core's memory database is designed to be consistent with the actual relational database. It is also controlled by the serviceprovider scope. In other words, under the same serviceprovider, the data in the memory database is kept "persistent" (in memory, of course) as the data of the relational database. This leads to the use of in-memory databases for unit testing, and there are two scenarios to consider:

1, each data operation involved in the unit test is completely isolated.

In this case, the instructions in the official documentation (HTTPS://GITHUB.COM/ASPNET/ENTITYFRAMEWORK.DOCS/ISSUES/95) can be used to instantiate or inject servicecollection, The DbContext instance is then obtained from the new serviceprovider each time the database is manipulated. The specific code is as follows:

usingMicrosoft.Data.Entity;usingMicrosoft.Data.Entity.Infrastructure;usingMicrosoft.Extensions.DependencyInjection;usingSystem;usingSystem.Linq;namespaceconsoleapp1{ Public classprogram { Public Static voidMain (string[] args) {var servicecollection =NewServicecollection (); Servicecollection. Addentityframework (). Addinmemorydatabase (). Adddbcontext<samplecontext> (c = c.useinmemorydatabase ());using(var db = Servicecollection.buildserviceprovider (). Getservice<samplecontext> ()) {db. Blogs.add (NewBlog {URL ="Test"}); Db.                SaveChanges (); Console.WriteLine (db.            Blogs.count ()); }using(var db = Servicecollection.buildserviceprovider (). Getservice<samplecontext> ()) {db. Blogs.add (NewBlog {URL ="Test"}); Db.                SaveChanges (); Console.WriteLine (db.            Blogs.count ()); }        }    } Public classSamplecontext:dbcontext { PublicDbset<blog> Blogs {get; set;} } Public classBlog { Public intBlogId {get; set;} Public stringURL {get; set;} }}

2, the unit test involves each data operation, the data needs to simulate the real unique database.

In a nutshell, I need to insert some sample data in a testfixture, and then each unit test will follow these sample data. In this case, in order to avoid encountering "inaccessible objects", it is necessary to obtain dbcontext in scoped by unifying the serviceprovider (which explains why it needs to be unified) to avoid the previous dbcontext being freed. This way, the official also has reference code, specifically I will not post, see (Https://github.com/aspnet/MusicStore/blob/dev/src/MusicStore/Models/SampleData.cs). Here is a sample code that I gave (see the code Snippet: HTTP://GIT.OSCHINA.NET/IKE/CODES/T069NO34DFU8P2ZEAHRSV):

     Public classefcoreinmemorytest {[Fact] PublicAsync Task Willsuccesswithwrongapproach () {var servicecollection =NewServicecollection (); Servicecollection. Addentityframework (). Addinmemorydatabase (). adddbcontext<marketdbcontext> (options = options.            Useinmemorydatabase ());            var serviceprovider = Servicecollection.buildserviceprovider ();            var db = serviceprovider.getrequiredservice<marketdbcontext> ();            Sampledata.create (DB);            var db2 = serviceprovider.getrequiredservice<marketdbcontext> (); var products = await DB2.            Products.tolistasync (); Assert.equal (3, products.            Count); var promotions = await DB2.            Promotions.tolistasync (); Assert.equal (2, promotions.        Count); } [Fact] PublicAsync Task Willfaild () {var servicecollection =NewServicecollection (); Servicecollection. Addentityframework (). Addinmemorydatabase (). adddbcontext<marketdbcontext> (options = options.            Useinmemorydatabase ()); var serviceprovider = Servicecollection.buildserviceprovider ();using(var db = serviceprovider.getrequiredservice<marketdbcontext> ())            {sampledata.create (db); }using(var db2 = serviceprovider.getrequiredservice<marketdbcontext> ()) {var products = await DB2.                Products.tolistasync (); Assert.equal (3, products.                Count); var promotions = await DB2.                Promotions.tolistasync (); Assert.equal (2, promotions.            Count); }} [Fact] PublicAsync Task Willsuccesswithrightapproach () {var servicecollection =NewServicecollection (); Servicecollection. Addentityframework (). Addinmemorydatabase (). adddbcontext<marketdbcontext> (options = options.            Useinmemorydatabase ());            var serviceprovider = Servicecollection.buildserviceprovider ();            Dodbactioninscoped (ServiceProvider, (db) + = {sampledata.create (db);            }); Await Dodbactioninscopedasync (serviceprovider, Async (DB2) and {var products = await DB2.                Products.tolistasync (); Assert.equal (3, products.                Count); var promotions = await DB2.                Promotions.tolistasync (); Assert.equal (2, promotions.            Count);        }); }Private voiddodbactioninscoped (IServiceProvider serviceprovider, action<marketdbcontext> Action) {using(var servicescope = serviceprovider.getrequiredservice<iservicescopefactory> (). Createscope ()) {using(var db = servicescope.serviceprovider.getrequiredservice<marketdbcontext> ())                {action (db); }            }        }PrivateAsync Task Dodbactioninscopedasync (IServiceProvider serviceprovider, Func<marketdbcontext, Task> action) {using(var servicescope = serviceprovider.getrequiredservice<iservicescopefactory> (). Createscope ()) {using(var db = servicescope.serviceprovider.getrequiredservice<marketdbcontext> ())                {await action (db); }            }        }    }

Another discussion on the EF core Memory Database Unit test problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.