我是 NSubstitute 的新手,正在尝试伪造一个名为 OrgDataWS
的现有类。此类有一个名为 GetDataSet
的方法:
public XmlElement GetDataSet(int token)
{
string perfLogMessage = string.Format("Org.GetDataSet: {0}", Guid.NewGuid().ToString());
MultiMessagePerformanceCounter performanceCounter = MultiMessagePerformanceCounter.StartNew(perfLogMessage);
XmlElement result = orgDataManager.GetDataSet(token);
performanceCounter.Stop();
return result;
}
以下是我的测试方法:
[TestMethod]
public void GetDataSetTest()
{
var dataWSStub = Substitute.For<OrgDataWS>();
var orgManagerStub = Substitute.For<OrgDataManager>();
var document = new XmlDocument();
var xmlElement = document.CreateElement("a");
orgManagerStub.GetDataSet(Arg.Any<int>()).Returns<XmlElement>(xmlElement);
dataWSStub.OrgDataManager = orgManagerStub;
var result = dataWSStub.GetDataSet(99);
}
但是,当我运行我的测试方法时,这一行
orgManagerStub.GetDataSet(Arg.Any<int>()).Returns<XmlElement>(xmlElement);
抛出异常。此异常来自 OrgDataManager
类的实现,根据我的理解,这不应该发生。使用该子句的目的是我希望如果使用任何 Int
参数调用 orgManagerStub
的 DataDataSet
方法,只需返回我的 xmlElement
实例。我不希望我的代码运行 OrgDataManager
的详细实现。
我的测试代码有什么问题?如何解决?
最佳答案
根据 the documentation :
Warning: Substituting for classes can have some nasty side-effects. For starters, NSubstitute can only work with virtual members of the class, so any non-virtual code in the class will actually execute! If you try to substitute for your class that formats your hard drive in the constructor or in a non-virtual property setter then you’re asking for trouble. If possible, stick to substituting interfaces.
(我的重点)
您显示的声明不是虚拟的,因此解决方案是为它创建一个接口(interface)并替换它,或者至少使该方法成为虚拟的(可能还有其他方法)。
关于c# - 如何在 NSubstitute 中伪造一个对象并忽略其方法的内部实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25480628/