-->

System.NotSupportedException: Invalid setup on a n

2020-03-07 04:53发布

问题:

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.