Moq DbSet NotImplementedException

送分小仙女□ 提交于 2019-12-30 23:46:39

问题


I have a Moq DbSet that has been working until recently, however since the last update of dependencies it keeps throwing a NotImplementedException on IQueryable.Provider

Code used as follows:

var mockSet = new Mock<DbSet<A>>();
var list = new List<A>();
var queryable = list.AsQueryable();
mockSet.As<IQueryable<A>>().Setup(m => m.Provider).Returns(queryable.Provider);
mockSet.As<IQueryable<A>>().Setup(m => m.Expression).Returns(queryable.Expression);
mockSet.As<IQueryable<A>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
mockSet.As<IQueryable<A>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());

var f =mockSet.Object.FirstOrDefault(); // NotImplementedException thrown here

The exception thrown as follows:

System.NotImplementedException
The member 'IQueryable.Provider' has not been implemented on type
'DbSet`1Proxy_1' which inherits from 'DbSet`1'.
Test doubles for 'DbSet`1' must provide implementations of methods
and properties that are used.

回答1:


Chances are that you have been using version 4.7.58 of Moq. That particular version was affected by a regression that would have triggered such a NotImplementedException. That regression has been fixed in version 4.7.63, so I suggest you update your Moq package reference to version 4.7.63 or newer to resolve this issue.

The fact that your code would have worked in Moq versions before 4.7.58 was due to a "feature" which unfortunately caused a lot more problems than it solved. For this reason, that feature was reverted.

Moq has been brought back to its original behaviour, where, in this particular scenario, you need to set up the various interface members via mock.As<TInterface> before the call to mock.Object. (Usually, in Moq, it's perfectly fine to perform more set ups even after retrieving the mock object; this scenario is a notable exception. Hopefully this can be fixed in a future version of Moq.)




回答2:


Rolling back Castle.Core to 4.0.0 and Moq to the latest version supporting 4.0.0 solved the issue. I'm still wondering if there is something I've missed that would fix this problem in the new version.



来源:https://stackoverflow.com/questions/46244563/moq-dbset-notimplementedexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!