甚至简单的Moq代码都引发NotSupportedException [英] Even simple Moq code is throwing NotSupportedException
问题描述
我一直在努力使用Moq作为模拟框架,并复制了一些非常简单的示例代码.我一定在这里缺少真正愚蠢的东西.即使它指向Returns方法,它也会在Setup调用上引发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());
}
推荐答案
您可以使用 typemock 隔离器,您无需更改源代码就可以轻松做到这一点.
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);
}
这篇关于甚至简单的Moq代码都引发NotSupportedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!