Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

C#Unit TestingMoq

C# Problem Overview


I have a unit test where I have to mock a non-virtual method that returns a bool type

public class XmlCupboardAccess
{
    public bool IsDataEntityInXmlCupboard(string dataId,
                                          out string nameInCupboard,
                                          out string refTypeInCupboard,
                                          string nameTemplate = null)
    {
        return IsDataEntityInXmlCupboard(_theDb, dataId, out nameInCupboard, out refTypeInCupboard, nameTemplate);
    }
}

So I have a mock object of XmlCupboardAccess class and I am trying to setup mock for this method in my test case as shown below

[TestMethod]
Public void Test()
{
    private string temp1;
    private string temp2;
    private Mock<XmlCupboardAccess> _xmlCupboardAccess = new Mock<XmlCupboardAccess>();
    _xmlCupboardAccess.Setup(x => x.IsDataEntityInXmlCupboard(It.IsAny<string>(), out temp1, out temp2, It.IsAny<string>())).Returns(false); 
    //exception is thrown by this line of code
}

But this line throws exception

Invalid setup on a non-virtual (overridable in VB) member: 
x => x.IsDataEntityInXmlCupboard(It.IsAny<String>(), .temp1, .temp2, 
It.IsAny<String>())

Any suggestion how to get around this exception?

C# Solutions


Solution 1 - C#

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

Solution 2 - C#

As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.

var mockFileBrowser = new Mock<FileBrowser>();

instead of

var mockFileBrowser = new Mock<IFileBrowser>();

Solution 3 - C#

Instead of mocking concrete class you should mock that class interface. Extract interface from XmlCupboardAccess class

public interface IXmlCupboardAccess
{
    bool IsDataEntityInXmlCupboard(string dataId, out string nameInCupboard, out string refTypeInCupboard, string nameTemplate = null);
}

And instead of

private Mock<XmlCupboardAccess> _xmlCupboardAccess = new Mock<XmlCupboardAccess>();

 

change to

private Mock<IXmlCupboardAccess> _xmlCupboardAccess = new Mock<IXmlCupboardAccess>();

Solution 4 - C#

Please see Why does the property I want to mock need to be virtual?

You may have to write a wrapper interface or mark the property as virtual/abstract as Moq creates a proxy class that it uses to intercept calls and return your custom values that you put in the .Returns(x) call.

Solution 5 - C#

You'll get this error as well if you are verifying that an extension method of an interface is called.

For example if you are mocking:

var mockValidator = new Mock<IValidator<Foo>>();
mockValidator
  .Verify(validator => validator.ValidateAndThrow(foo, null));

You will get the same exception because .ValidateAndThrow() is an extension on the IValidator<T> interface.

public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet = null)...

Solution 6 - C#

In my case I was on Moq version lower than 4.16 and was using .Result syntax to mock an async method which is supported only starting with Moq 4.16

On mock version less than 4.16 following results into Invalid setup on a non-virtual member ... even while using Interface.

mock.Setup(foo => foo.DoSomethingAsync().Result).Returns(true);

On Moq version lower than 4.16 use following

mock.Setup(foo => foo.DoSomethingAsync()).ReturnsAsync(true);

For more see Async Methods Moq Wiki at Github

Solution 7 - C#

Code:

private static void RegisterServices(IKernel kernel)
{
    Mock<IProductRepository> mock=new Mock<IProductRepository>();
    mock.Setup(x => x.Products).Returns(new List<Product>
    {
        new Product {Name = "Football", Price = 23},
        new Product {Name = "Surf board", Price = 179},
        new Product {Name = "Running shose", Price = 95}
    });

    kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}        

but see exception.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRahul LodhaView Question on Stackoverflow
Solution 1 - C#AmolView Answer on Stackoverflow
Solution 2 - C#RaltView Answer on Stackoverflow
Solution 3 - C#SashusView Answer on Stackoverflow
Solution 4 - C#BryidaView Answer on Stackoverflow
Solution 5 - C#Scotty.NETView Answer on Stackoverflow
Solution 6 - C#TheCrazyProgrammerView Answer on Stackoverflow
Solution 7 - C#BoratView Answer on Stackoverflow