fingers10
fingers10

Reputation: 7977

Moq - Non-overridable members may not be used in setup / verification expressions

I'm new to Moq. I'm mocking a PagingOptions class. Here is how the class looks like:

public class PagingOptions
    {
        [Range(1, 99999, ErrorMessage = "Offset must be greater than 0.")]
        public int? Offset { get; set; }

        [Range(1, 100, ErrorMessage = "Limit must be greater than 0 and less than 100.")]
        public int? Limit { get; set; }

        public PagingOptions Replace(PagingOptions newer)
        {
            return new PagingOptions
            {
                Offset = newer.Offset ?? Offset,
                Limit = newer.Limit ?? Limit
            };
        }
    }

Here is my mock version of the class,

var mockPagingOptions = new Mock<PagingOptions>();
            mockPagingOptions.Setup(po => po.Limit).Returns(25);
            mockPagingOptions.Setup(po => po.Offset).Returns(0);

I get the below error when setting up the property values. Am I making something wrong. Looks like I cannot Moq concrete class? Only Interfaces can be Mocked? Please assist.

moq error

Thanks, Abdul

Upvotes: 193

Views: 236952

Answers (7)

Cagin Uludamar
Cagin Uludamar

Reputation: 476

In my case I was mocking a public method which was not virtual. Making the method virtual made the trick.

As an old Java developer, I'm used to the approach that all public methods are already virtual, there is no need to mark them separately as virtual so that sub classes can override them. C# is different here.

Maybe someone can explain if it is ok to mark a public method in a production code as virtual for testing purposes in C#.

Edit: I've come across the official EF Core documentation which recommends making DbSet properties of a DbContext virtual for testing, so maybe this is not a bad practice.

Upvotes: 5

pizzaboy
pizzaboy

Reputation: 1032

Late for the party, but I brought some tasty cake for those who are still hungry. I've found there's a specific SetupGet that allows you to mock getters. It does not require any code change on the class side.

var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.SetupGet(po => po.Limit).Returns(25);
mockPagingOptions.SetupGet(po => po.Offset).Returns(0);

There's also a SetupSet version, which takes care of the Setters.

Upvotes: 0

user3153326
user3153326

Reputation: 51

On occasion you may be working with a class from a third party library that has properties which can be directly set or mocked.

Where the answer by above is not sufficient you can also invoke the setter method directly, for example where a class has a property called "Id" with no accessible setter:

var idSetter = account.GetType().GetMethod("set_Id", BindingFlags.Instance | BindingFlags.NonPublic);

idSetter!.Invoke(account, new[] { "New ID Here" });

Upvotes: 3

No Refunds No Returns
No Refunds No Returns

Reputation: 8356

In case you reached this question based on the original title Non-overridable members may not be used in setup / verification expressions and none of the other answers have helped you may want to see if reflection can satisfy your test needs.

Suppose you have a class Foo with a property defined as public int I { get; private set; }

If you try the various methods in the answers here few of them will work for this scenario. However you can use .net reflection to setup a value of an instance variable and still keep fairly good refactoring support in the code.

Here is a snippet that sets a property with a private setter:

var foo = new Foo();
var I = foo.GetType().GetProperty(nameof(Foo.I), BindingFlags.Public | BindingFlags.Instance);
I.SetValue(foo, 8675309);

I do not recommend this for production code. It has proven very useful in numerous tests for me. I found this approach a few years ago but needed to look it up again recently and this was the top search result.

Upvotes: 21

Scott Hannen
Scott Hannen

Reputation: 29302

Moq creates an implementation of the mocked type. If the type is an interface, it creates a class that implements the interface. If the type is a class, it creates an inherited class, and the members of that inherited class call the base class. But in order to do that it has to override the members. If a class has members that can't be overridden (they aren't virtual, abstract) then Moq can't override them to add its own behaviors.

In this case there's no need to mock PagingOptions because it's easy to use a real one. Instead of this:

var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.Setup(po => po.Limit).Returns(25);
mockPagingOptions.Setup(po => po.Offset).Returns(0);

Do this:

var pagingOptions = new PagingOptions { Limit = 25, Offset = 0 };

How do we determine whether or not to mock something? Generally speaking, we mock something if we don't want to include the concrete runtime implementation in our test. We want to test one class not both at the same time.

But in this case PagingOptions is just a class that holds some data. There's really no point in mocking it. It's just as easy to use the real thing.

Upvotes: 261

Ali Karaca
Ali Karaca

Reputation: 3871

I want to improve Scott's answer and give a general answer

If the type is a class, it creates an inherited class, and the members of that inherited class call the base class. But in order to do that it has to override the members. If a class has members that can't be overridden (they aren't virtual, abstract) then Moq can't override them to add its own behaviors.

In my situation i had to make the prop virtual. So answer to your class code is:

public class PagingOptions {
    [Range (1, 99999, ErrorMessage = "Offset must be greater than 0.")]
    public virtual int? Offset { get; set; }

    [Range (1, 100, ErrorMessage = "Limit must be greater than 0 and less than 100.")]
    public virtual int? Limit { get; set; }

    public PagingOptions Replace (PagingOptions newer) {
        return new PagingOptions {
            Offset = newer.Offset ?? Offset,
                Limit = newer.Limit ?? Limit
        };
    }
}

use same:

var mockPagingOptions = new Mock<PagingOptions>();
        mockPagingOptions.Setup(po => po.Limit).Returns(25);
        mockPagingOptions.Setup(po => po.Offset).Returns(0);

Upvotes: 16

Telmo Trooper
Telmo Trooper

Reputation: 5694

I had the same error, but in my case I was trying to mock the class itself and not its interface:

// Mock<SendMailBLL> sendMailBLLMock = new Mock<SendMailBLL>(); // Wrong, causes error.
Mock<ISendMailBLL> sendMailBLLMock = new Mock<ISendMailBLL>();  // This works.

sendMailBLLMock.Setup(x =>
    x.InsertEmailLog(
        It.IsAny<List<EmailRecipient>>(),
        It.IsAny<List<EmailAttachment>>(),
        It.IsAny<string>()));

Upvotes: 91

Related Questions