C # decoupling entityframework for unit testing

Source: Internet
Author: User
1. First the repository of EF requires an abstraction of the behavior mentioned in the interface.

For example:

Public interface ixxxcontext:idisposable    {        ixxxcontext newinstance ();//DB sets        dbset<aaabbb> AAA { Get Set }...//Common Database Database {get;}        Dbcontextconfiguration Configuration {get;}        int SaveChanges ();        Task<int> Savechangesasync ();//Store Pros        ... IStorePro1 StorePro1 {get;} ...}


You can then implement this interface using DataContext and Testdatacontext. Where Testdatacontext is used in UT, DataContext is automatically generated.

Testdatacontext also requires the following classes for simulation.

 public class testdbset<tentity>: Dbset<tentity>, IQueryable, Ienumerable<tentity>,        idbasyncenumerable<tentity> where Tentity:class {observablecollection<tentity> _data;        IQueryable _query;            Public Testdbset () {_data = new observablecollection<tentity> (); _query = _data.        AsQueryable (); } public override TEntity Add (TEntity item) {_data.            ADD (item);        return item; } public override TEntity Remove (TEntity item) {_data.            Remove (item);        return item; } public override TEntity Attach (TEntity item) {_data.            ADD (item);        return item;        } public override TEntity Create () {return activator.createinstance<tentity> (); } public override Tderivedentity create<tderivedentity> () {return activator.createinstance<TDerivedEntity> ();        } public override observablecollection<tentity> Local {get {return _data;} } Type Iqueryable.elementtype {get {return _query. ElementType; }} Expression iqueryable.expression {get {return _query. Expression; }} Iqueryprovider Iqueryable.provider {get {return new testdbasyncqueryprovider<tent Ity> (_query. Provider);  }} System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {return _data.        GetEnumerator (); } ienumerator<tentity> Ienumerable<tentity>. GetEnumerator () {return _data.        GetEnumerator (); } idbasyncenumerator<tentity> Idbasyncenumerable<tentity>. Getasyncenumerator () {return new testdbasyncenumerator<tentity> (_data.        GetEnumerator ()); }} internal class Testdbasyncqueryprovider<tentity>: idbasyncqueryprovider {private readonly iqueryprovider _inner;        Internal Testdbasyncqueryprovider (Iqueryprovider inner) {_inner = inner; } public IQueryable createquery (expression expression) {return new testdbasyncenumerable<tent        ity> (expression); } public iqueryable<telement> createquery<telement> (expression expression) {return n        EW testdbasyncenumerable<telement> (expression); public object Execute (expression expression) {return _inner.        Execute (expression); Public TResult execute<tresult> (expression expression) {return _inner.        execute<tresult> (expression);            } public task<object> Executeasync (expression expression, CancellationToken CancellationToken) {        Return Task.fromresult (Execute (expression)); }        Public task<tresult> executeasync<tresult> (expression expression, CancellationToken CancellationToken)        {return Task.fromresult (execute<tresult> (expression)); }} internal class testdbasyncenumerable<t>: Enumerablequery<t>, Idbasyncenumerable<t>, IQueryabl        e<t> {public testdbasyncenumerable (ienumerable<t> enumerable): Base (enumerable) {} public testdbasyncenumerable (expression expression): base (expression) {} public Idba Syncenumerator<t> Getasyncenumerator () {return new testdbasyncenumerator<t> (this. AsEnumerable ().        GetEnumerator ());        } idbasyncenumerator Idbasyncenumerable.getasyncenumerator () {return getasyncenumerator (); } iqueryprovider Iqueryable.provider {get {return new testdbasyncqueryprovider<t> (this ); }}} InternaL class Testdbasyncenumerator<t>: idbasyncenumerator<t> {private readonly ienumerator<t> _in        Ner        Public Testdbasyncenumerator (ienumerator<t> inner) {_inner = inner; public void Dispose () {_inner.        Dispose (); } public task<bool> Movenextasync (CancellationToken cancellationtoken) {return task.fromre Sult (_inner.        MoveNext ()); } public T-current {get {return _inner. Current;        }} object Idbasyncenumerator.current {get {return current;} }    }


Examples of Use:

[TestMethod]        public void TestMethod1 ()        {            var mockset = new mock<dbset<blacklisted_ticket>> ();            var mockcontext = new mock<ticketdatacontexttest> ();            Mockcontext.setup (M = m.blacklisted_ticket). Returns (New testdbset<blacklisted_ticket> ());            var context = Mockcontext.object;            Context. Blacklisted_ticket. ADD (New Blacklisted_ticket ()            {                ticketnumber = "AAA",                createddatetime = DateTime.Now,                Id = 1,                Modifieddatetime = DateTime.Now,                STATUS = "1"            });            Assert.istrue (context. Blacklisted_ticket. First (). Id = = 1);        }

If you use a stored procedure, you need an additional interface to define the stored procedure.
For example:

Istorepro {...} Storepro:istorepro{...} storeprofake:istorepro{}

Then Idatacontext is responsible for returning the instance of the stored procedure

idatacontext{... Istorepro Getstorepro (); ...}

The above is the C # decoupling entityframework unit test content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.