甚至简单的Moq代码都抛出NotSupportedException

MrF*_*Fox 2 c# unit-testing moq

我一直在努力使用Moq作为模拟框架,并复制了一些非常简单的示例代码。我一定在这里缺少真正愚蠢的东西。即使它指向Returns方法,它也会在Setup调用上引发NotSupportedException。这段代码是我的测试类的一部分:

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());
}
Run Code Online (Sandbox Code Playgroud)

dot*_*tom 5

异常错误消息可以提示您问题所在:

在非虚拟(在VB中可重写)成员上的无效设置

这意味着,当您模拟类的方法时,只能模拟抽象的或虚的类(在您的情况下两者都不是)。

因此,最简单的解决方法是将方法设为虚拟:

public virtual string DoSomethingStringy(string s)
{
    return s;
}
Run Code Online (Sandbox Code Playgroud)

  • 而且`class` 必须是`public`(`internal` 是可以的,只有你在某处有一个合适的`InternalsVisibleToAttribute`)。 (2认同)