老问题,但由于我在搜索时找到了它,我会用我的解决方案为下一个人回答它。
在大多数情况下,使用MolesContext.ExecuteWithoutMoles
调用原始函数可以正常工作,但是,如果您在此调用的下游添加任何其他函数或类,它们也不会被添加。
给定以下课程:
public class TheClass
{
public int TheFunction(int input){
return input + TheOtherFunction();
}
public int TheOtherFunction(){
return DateTime.Now.Minutes;
}
}
如果您使用该MolesContext.ExecuteWithoutMoles
方法:
MTheClass.AllInstances.TheOtherFunctionInt = (instance) => {
return 5;
};
MTheClass.AllInstances.TheFunctionInt = (instance, input) =>
{
//do your stuff here, for example:
Debug.WriteLine(input.ToString());
var result = MolesContext.ExecuteWithoutMoles<int>(() => instance.TheFunction(input));
//do more stuff, if desired
return result;
};
您的 OtherFunction 的痣不会被击中,因为它是在“无痣”范围内(间接)执行的。
但是,您可以随时添加和删除 moles 代表,以便您执行以下操作,如Moles 文档(p. 24)中所述
MTheClass.AllInstances.TheOtherFunctionInt = (instance) => {
return 5;
};
MolesDelegates.Func<TheClass, int, int> molesDelegate = null;
molesDelegate = (instance, input) =>
{
//do your stuff here, for example:
Debug.WriteLine(input.ToString());
int result = 0;
try{
MTheClass.AllInstances.TheFunctionInt = null;
result = instance.TheFunction(input);
}
finally{
MTheClass.AllInstances.TheFunctionInt = molesDelegate;
}
//do more stuff, if desired
return result;
};
MTheClass.AllInstances.TheFunctionInt = molesDelegate;
OtherFunction 痣仍然被击中。使用这种方法,您可以仅从特定方法中去除痣,而不会影响其他痣。我用过这个,它有效。我能看到的唯一麻烦是,如果你有递归函数,或者可能是多线程情况,它就不起作用。