MrFox MrFox - 13 days ago 6
C# Question

Even simple Moq code is throwing NotSupportedException

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());
}

Answer

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;
}