3

I've been struggling to use Moq as a mocking framework and copied some very simple example code. I must be missing something really stupid here. It throws a NotSupportedException on the Setup call, even though it points to the Returns method. This code is part of my tests class:

class Test
{
    public string DoSomethingStringy(string s)
    {
        return s;
    }
}

[TestInitialize]
public void Setup()
{
    var mock = new Mock<Test>();
    mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>()))
        .Returns((string s) => s.ToLower());
}
MrFox
  • 4,852
  • 7
  • 45
  • 81

2 Answers2

7

The Exception error message can give you a hint what the issue is:

Invalid setup on a non-virtual (overridable in VB) member

This means that when you are mocking method of a class, you can only mock it if is abstract or virtual (in your case it is neither).

So the simplest fix would be to make the method virtual:

public virtual string DoSomethingStringy(string s)
{
    return s;
}
dotnetom
  • 24,551
  • 9
  • 51
  • 54
2

You can mock non-virtual object with typemock isolator, and you can do so without changing your source code and quite easily.

By just creating a fake instance of your under test object and determine a new behavior for the tested method.

For example I've created a test for the code you posted:

  [TestMethod]
        public void TestMethod1()
        {
            var mock = Isolate.Fake.Instance<Test>();
            Isolate.WhenCalled(() => mock.DoSomethingStringy(null)).DoInstead(contaxt =>
            {
                return (contaxt.Parameters[0] as string).ToLower();
            });

            var res = mock.DoSomethingStringy("SOMESTRING");

            Assert.AreEqual("somestring", res);
        } 
Gregory Prescott
  • 574
  • 3
  • 10