166

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

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
fingers10
  • 6,675
  • 10
  • 49
  • 87
  • 7
    Make the properties `Offset` and `Limit ` virtual. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual – Jordan Bowker Jul 05 '19 at 15:18
  • 10
    In this case it doesn't seem like there's a reason to mock this. You can just create an actual instance of `PagingOptions` and set its properties instead of using a `Mock`. Don't make anything virtual. – Scott Hannen Jul 05 '19 at 15:18
  • 3
    unless this is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) I see no need to mock this object. There appears to be no obvious knock on effects of using the object as is that would warrant having to create a mock – Nkosi Jul 05 '19 at 15:22
  • @ScottHannen How to find which object to mock and which not to mock? how are you differentiating? – fingers10 Jul 05 '19 at 15:25
  • 1
    @AbdulRahman https://stackoverflow.com/a/38256/5233410 – Nkosi Jul 05 '19 at 15:30

6 Answers6

229

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.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • 1
    Although this works if these are the only properties/methods you want to test, it doesn't if you want to predict other properties/methods behavior in pagingOptions. – Luis Gouveia Mar 31 '21 at 13:51
  • I don't agree with the approach that you can just use the real class. I believe that the only real class that should be created in the unit test is the class under the test, all it's dependencies should be mocked, does not matter if they are complex or not, developer shouldn't have to look inside the dependency class to assed if it should be mocked or not causes this will confuse others that follow and will see places where mocks are used and not. The rules must be simple and deterministic for others to follow them. Also what if the instance changes in time and creates file on the drive ? – IronHide Mar 22 '23 at 18:52
  • Forced consistency for the sake of consistency is a root of evil. No one will be confused because someone used a mock where they needed one but not where they didn't need one. https://scotthannen.org/blog/2020/10/14/consistency.html – Scott Hannen Mar 22 '23 at 21:29
79

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>()));
Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35
  • That helps a lot. Thank you so much. In case you want to set some operation, `obj.Setup(...).Returns(/*mock implementation*/);` ref: https://stackoverflow.com/questions/41351543/mock-a-class-in-a-class-in-a-unit-test – Devendra Lattu Jan 29 '21 at 20:43
  • 1
    As stupid as it seems, this was my problem as well. Helpful to double check if you are using the interface, before digging deeper what could possible have gone wrong. – typhon04 Feb 08 '21 at 08:30
  • I was having the same problem, many thanks for your valuable answer. It works for me using interface instead, exactly the way you have mentioned in the code block. Thumb sup. – Burhan Jul 15 '21 at 00:35
  • 1
    This should be the actually accepted answer. It is considered a best practice to use interfaces when mocking inside of your unit tests, so that pieces can be removed and replaced flexibly. Also, it makes sense with what Moq is doing behind the scenes, creating a class that fits the defined interface and redefining the behavior of different class members. – JLunda Dec 29 '21 at 02:39
  • I had to change a lot of my internal dependencies to have this implemented, but am very happy after doing that.. Code looks so much SOLID – NitinSingh Apr 27 '22 at 20:14
15

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.

FoxDeploy
  • 12,569
  • 2
  • 33
  • 48
No Refunds No Returns
  • 8,092
  • 4
  • 32
  • 43
14

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);
Ali Karaca
  • 3,365
  • 1
  • 35
  • 41
  • 35
    yes but now you're modifying a property accessor just for testability sake – Poat Sep 29 '20 at 16:46
  • 8
    yes but you have to if you want to mock it – Ali Karaca Jul 30 '21 at 07:05
  • 7
    Should be noted that official MS docs have the DbSet properties marked as virtual for this specific purpose: https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking#the-ef-model – Finster Aug 03 '21 at 19:24
  • 2
    You could modify a property accessor just for testability or add an interface just for testability. Which is more desireable depends on circumstance. I all the time mark things internal and "share internals to" just for testability... – Denise Skidmore Sep 08 '22 at 23:27
1

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" });
0

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#.

Cagin Uludamar
  • 372
  • 1
  • 3
  • 16