In XUnit, how does one use Moq to simulate DbSet under EntityFramework Core,

Source: Internet
Author: User
Tags xunit

In XUnit, how does one use Moq to simulate DbSet under EntityFramework Core,

I recently encountered some problems in the unit test of a project. After solving these problems, I felt it was necessary to write them down and share them with the people who needed them. Let's briefly explain the background of the project's technical framework:

  • Asp.net core 2.0 (for. net core) Framework
  • Using Entity Framework Core for ORM
  • XUnit unit test
  • Moq as an isolation box

During unit tests on the business layer, because the business layer calls the data processing layer, it is easy to use Moq to simulate DbContext, however, if you operate the extension methods in DbSet and DbSet under DbContext, a System is thrown. notSupportedException exception. This is because we cannot Mock DbSet, and help DbSet to be an abstract class, and there is no way to instantiate it.

In fact, what we hope at this time is that if we use a general set, such as the List <T> set or the T [] array to Mock DbSet <T>, it will be very comfortable, because the elements of a set or array are very easy to simulate or control, unlike DbSet.

These common extension methods in DbSet are: Where, Select, SingleOrDefault, FirstOrDefault, OrderBy, and so on. They all extend IQueryable, that is to say, it is okay to call the extension methods of DbSet to Mock List <T> or T,

The following types are implemented:

Project needs to be introduced: Microsoft. EntityFrameworkCore and Moq. Nuget can be introduced.

UnitTestAsyncEnumerable. cs

1 using System. collections. generic; 2 using System. linq; 3 using System. linq. expressions; 4 5 namespace MoqEFCoreExtension 6 {7 // <summary> 8 // custom implementation EnumerableQuery <T>, IAsyncEnumerable <T>, IQueryable <T> type 9 /// </summary> 10 // <typeparam name = "T"> </typeparam> 11 class UnitTestAsyncEnumerable <T>: enumerableQuery <T>, IAsyncEnumerable <T>, IQueryable <T> 12 {13 public UnitTestAsyncEnumerable (IEnumerable <T> enumerable) 14: base (enumerable) 15 {} 16 17 public UnitTestAsyncEnumerable (Expression expression) 18: base (expression) 19 {} 20 21 public IAsyncEnumerator <T> GetEnumerator () 22 {23 return new UnitTestAsyncEnumerator <T> (this. asEnumerable (). getEnumerator (); 24} 25 26 IQueryProvider IQueryable. provider27 {28 get {return new UnitTestAsyncQueryProvider <T> (this);} 29} 30} 31}

UnitTestAsyncEnumerator. cs

1 using System. collections. generic; 2 using System. threading; 3 using System. threading. tasks; 4 5 namespace MoqEFCoreExtension 6 {7 // <summary> 8 // define the IAsyncEnumerator <T> type 9 /// </summary> 10 // <typeparam name = "T"> </typeparam> 11 class UnitTestAsyncEnumerator <T>: IAsyncEnumerator <T> 12 {13 private readonly IEnumerator <T> _ inner; 14 15 public UnitTestAsyncEnumerator (IEnumerator <T> inner) 16 {17 _ inner = inner; 18} 19 20 public void Dispose () 21 {22 _ inner. dispose (); 23} 24 25 public T Current26 {27 get28 {29 return _ inner. current; 30} 31} 32 33 public Task <bool> MoveNext (CancellationToken cancellationToken) 34 {35 return Task. fromResult (_ inner. moveNext (); 36} 37} 38}

UnitTestAsyncQueryProvider. cs

1 using Microsoft. entityFrameworkCore. query. internal; 2 using System. collections. generic; 3 using System. linq; 4 using System. linq. expressions; 5 using System. threading; 6 using System. threading. tasks; 7 8 namespace MoqEFCoreExtension 9 {10 /// <summary> 11 /// implement IQueryProvider interface 12 /// </summary> 13 /// <typeparam name = "TEntity"> </typeparam> 14 class UnitTestAsyncQueryProvider <TEntity>: IAsyncQueryProvider15 {16 private readonly IQueryProvider _ inner; 17 18 internal UnitTestAsyncQueryProvider (IQueryProvider inner) 19 {20 _ inner = inner; 21} 22 23 public IQueryable CreateQuery (Expression expression Expression) 24 {25 return new UnitTestAsyncEnumerable <TEntity> (expression); 26} 27 28 public IQueryable <TElement> CreateQuery <TElement> (Expression) 29 {30 return new UnitTestAsyncEnumerable <TElement> (expression); 31} 32 33 public object Execute (Expression expression) 34 {35 return _ inner. execute (expression); 36} 37 38 public TResult Execute <TResult> (Expression expression) 39 {40 return _ inner. execute <TResult> (expression); 41} 42 43 public IAsyncEnumerable <TResult> ExecuteAsync <TResult> (Expression expression) 44 {45 return new UnitTestAsyncEnumerable <TResult> (expression ); 46} 47 48 public Task <TResult> ExecuteAsync <TResult> (Expression expression, CancellationToken cancellationToken) 49 {50 return Task. fromResult (Execute <TResult> (expression); 51} 52} 53}

Extended method class EFSetupData. cs

1 using Microsoft. entityFrameworkCore; 2 using Moq; 3 using System. collections. generic; 4 using System. linq; 5 6 7 namespace MoqEFCoreExtension 8 {9 // <summary> 10 // DbContext in Mock Entity Framework Core, load List <T> or T [] to DbSet <T> 11 // </summary> 12 public static class EFSetupData13 {14 /// <summary> 15 // list <T> to DbSet16 // </summary> 17 // <typeparam name = "T"> entity type </typeparam> 18 // <param name =" mockSet "> Mock <DbSet> Object </param> 19 // <param name =" list "> Object list </param> 20 /// <returns> </returns> 21 public static Mock <DbSet <T> SetupList <T> (this Mock <DbSet <T> mockSet, list <T> list) where T: class22 {23 return mockSet. setupArray (list. toArray ()); 24} 25 /// <summary> 26 // load data to DbSet27 /// </summary> 28 /// <typeparam name = "T"> entity type </ typeparam> 29 // <param name = "mockSet"> Mock <DbSet> Object </param> 30 /// <param name = "array"> Object array </param> 31 // <returns> </returns> 32 public static Mock <DbSet <T> SetupArray <T> (this Mock <DbSet <T> mockSet, params T [] array) where T: class33 {34 var queryable = array. asQueryable (); 35 mockSet. as <IAsyncEnumerable <T> (). setup (m => m. getEnumerator ()). returns (new UnitTestAsyncEnumerator <T> (queryable. getEnumerator (); 36 mockSet. as <IQueryable <T> (). setup (m => m. provider ). returns (new UnitTestAsyncQueryProvider <T> (queryable. provider); 37 mockSet. as <IQueryable <T> (). setup (m => m. expression ). returns (queryable. expression); 38 mockSet. as <IQueryable <T> (). setup (m => m. elementType ). returns (queryable. elementType); 39 mockSet. as <IQueryable <T> (). setup (m => m. getEnumerator ()). returns () => queryable. getEnumerator (); 40 return mockSet; 41} 42} 43}

Var answerSet = new Mock <DbSet <Answers> (). setupList (list); replace the extension method so that it is stored in answerRepository. when SingleOrDefault is called in ModifyAnswer (answer), the list with two answers is operated, instead of DbSet.

Source code and Sample: https://github.com/axzxs2001/MoqEFCoreExtension

At the same time, I closed this feature into a Nuget package, see: https://www.nuget.org/packages/MoqEFCoreExtension/

The last graph was shocked:

 

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.