我试图在我的项目中模拟静态函数。我无法使用Rhynomocks来实现这一点,因此尝试使用Typemock来模拟静态函数。
他们说使用typemock来模拟静态函数是很有必要的,下面给出了同样的例子。
http://www.typemock.com/basic-typemock-unit-testing
然而,它似乎对我不起作用。下面是我的代码:
公共类Class1Test { 隔离(设计= DesignMode.Pragmatic) 公共空函数() { Isolate.Fake.StaticMethods(Members.MustSpecifyReturnValues); Isolate.WhenCalled(() => LoggerFactory.Add(6,4)).WillReturn(11);int值= LoggerFactory.Add(5,6);}
-----------------------------------------------LoggerFactory.cs
公共类LoggerFactory {
public static int Add(int intx, int inty)
{
return intx + inty;
}
}我得到的错误是:
*在InterfaceOnly设计模式下,伪造非虚拟方法是不可能的。使用隔离(DesignMode.Pragmatic)来伪造这个。在这里了解更多http://www.typemock.com/isolator-design-mode
提前谢谢。
发布于 2012-10-31 21:48:04
您的示例代码看起来不完整。我只是使用您的代码将一个稍微修改过的复制放在一起,它工作得很好。具体来说,Isolate.Fake.StaticMethods调用缺少了您想要的模拟类型。
using System;
using NUnit.Framework;
using TypeMock.ArrangeActAssert;
namespace TypeMockDemo
{
public class LoggerFactory
{
public static int Add(int intx, int inty)
{
return intx + inty;
}
}
// The question was missing the TestFixtureAttribute.
[TestFixture]
public class LoggerFactoryFixture
{
// You don't have to specify DesignMode.Pragmatic - that's the default.
[Isolated(Design = DesignMode.Pragmatic)]
[Test]
public void Add_CanMockReturnValue()
{
// The LoggerFactory type needs to be specified here. This appeared
// missing in the example from the question.
Isolate.Fake.StaticMethods<LoggerFactory>(Members.MustSpecifyReturnValues);
// The parameters in the Add call here are totally ignored.
// It's best to put "dummy" values unless you are using
// WithExactArguments.
Isolate.WhenCalled(() => LoggerFactory.Add(0, 0)).WillReturn(11);
// Note the parameters here. No WAY they add up to 11. That way
// we know you're really getting the mock value.
int value = LoggerFactory.Add(100, 200);
// This will pass.
Assert.AreEqual(11, value);
}
}
}如果您可以将该代码粘贴到一个项目中(使用Typemock和NUnit引用),但是它不能工作,那么您可能在正确执行测试时遇到问题,或者您的机器上可能有错误配置。在这两种情况下,如果上面的代码不起作用,您可能希望联系Typemock支持。
发布于 2012-10-27 20:25:57
你为什么一开始就想伪装?您的方法不需要模拟,因为它是无状态的-只需直接测试它:
[Test]
public void Six_Plus_Five_Is_Eleven()
{
Assert.That(11, Is.EqualTo(LoggerFactory.Add(6, 5));
}https://stackoverflow.com/questions/13086870
复制相似问题