【问题标题】:Even simple Moq code is throwing NotSupportedException即使是简单的起订量代码也会抛出 NotSupportedException
【发布时间】:2016-11-27 11:37:31
【问题描述】:

我一直在努力将 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());
}

【问题讨论】:

    标签: c# unit-testing moq


    【解决方案1】:

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

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

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

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

    public virtual string DoSomethingStringy(string s)
    {
        return s;
    }
    

    【讨论】:

    • 另外class 必须是publicinternal 是可以的,只有你在某处有一个合适的InternalsVisibleToAttribute)。
    【解决方案2】:

    您可以使用typemock 隔离器模拟非虚拟对象,并且您可以在不更改源代码的情况下轻松地做到这一点。

    只需创建一个被测对象的假实例并确定被测方法的新行为。

    例如,我为您发布的代码创建了一个测试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      • 2014-12-25
      • 2019-09-09
      • 2021-11-28
      • 2015-02-19
      相关资源
      最近更新 更多