System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member

隐身守侯 提交于 2019-12-12 09:10:01

问题


I am getting a NotSupportedException error message on my Unit Test using Moq

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member

Unit Test Code:

[TestMethod]
public void TestEmailNotSentOut()
{
  // ...

  var dataAccess = new Mock<TjiContext>();       
  var mockSetStock = new Mock<DbSet<Stock>>();
  mockSetStock.As<IQueryable<Stock>>().Setup(m => m.Provider).Returns(stockList.Provider);
  mockSetStock.As<IQueryable<Stock>>().Setup(m => m.Expression).Returns(stockList.Expression);
  mockSetStock.As<IQueryable<Stock>>().Setup(m => m.ElementType).Returns(stockList.ElementType);
  mockSetStock.As<IQueryable<Stock>>().Setup(m => m.GetEnumerator()).Returns(stockList.GetEnumerator());
  dataAccess.Setup(m => m.Stocks).Returns(mockSetStock.Object);

A suggestion in this post says to mark it as virtual, but I'm not sure what needs to be marked as virtual?

The error is occurring at this line:

  dataAccess.Setup(m => m.Stocks).Returns(mockSetStock.Object);

回答1:


Assuming you're using EF of at least V6 and based on this example (look at the Blogs element) which is doing a very similar thing to you. I'd guess that your problem is that your dataAccess, whatever it is doesn't declare Stocks as virtual.

So it should look something like this:

public virtual DbSet<Stock> Stocks { get; set; } 



回答2:


The property or function you're trying to setup needs to be declared as

public virtual

otherwise Moq can't create an inherited class, which overrides this function or propterty, which is nessecary, when you want to setup it.



来源:https://stackoverflow.com/questions/30936349/system-notsupportedexception-invalid-setup-on-a-non-virtual-overridable-in-vb

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