Even simple Moq code is throwing NotSupportedException

天大地大妈咪最大 提交于 2020-01-24 13:15:15

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/40828489/even-simple-moq-code-is-throwing-notsupportedexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!