2

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);
Community
  • 1
  • 1
Frazer
  • 560
  • 2
  • 11
  • 21
  • 2
    At what line you are getting this error? – Amit Jun 19 '15 at 11:00
  • base on your code seems that you are using Entity framework. if so, the problematic line is ׳dataAccess.Setup(m => m.Stocks).Returns(mockSetStock.Object);׳. you can't fake this line using ׳Moq׳. (i believe dataAccess is StocksModelContext : DbContext{ public DbSet Stocks{ get; set; } }) – Old Fox Jun 19 '15 at 11:23
  • The error is occurring on line dataAccess.Setup(m => m.Stocks).Returns(mockSetStock.Object); I am using EntityFramework var dataAccess = new Mock(); public DbSet Stocks { get; set; } So can that line be changed or do i need to find another way to test without using Moq? – Frazer Jun 19 '15 at 11:54

2 Answers2

7

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; } 
forsvarir
  • 10,749
  • 6
  • 46
  • 77
-3

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.

LInsoDeTeh
  • 1,028
  • 5
  • 11
  • 1
    OP is aware of marking virtual. He is not aware of what thing to make virtual. – Amit Jun 19 '15 at 11:01
  • One of the properties he wants to setup, so either Provider, Expression, ElementType, or GetEnumerator(). And I think my explanation of what happens when mocking, helps him to determine which of these. – LInsoDeTeh Jun 19 '15 at 11:11