我猜你只能使用存根来实现这种行为。
这是一个代码示例。我们将调用MethodToTest
,所有其他方法都ClassUnderTest
将抛出类型异常BehaviorNotImplementedException
。
public class ClassUnderTest
{
public virtual void MethodToTest()
{
Debug.WriteLine("In MethodToTest");
AnotherMethod();
}
public virtual void AnotherMethod()
{
Debug.WriteLine("In AnotherMethod");
}
}
Moles 为我们生成了一个存根类,SClassUnderTest
我们将使用它来调用MethodToTest
.
public void Test1()
{
// A hack to call an overridden method.
var mi = typeof(ClassUnderTest).GetMethod("MethodToTest");
DynamicMethod dm = new DynamicMethod(
"BaseMethodToTest",
null,
new Type[] { typeof(SClassUnderTest) },
typeof(SClassUnderTest));
ILGenerator gen = dm.GetILGenerator();
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, mi);
gen.Emit(OpCodes.Ret);
var baseMethodCall = (Action<SClassUnderTest>)dm.CreateDelegate(
typeof(Action<SClassUnderTest>));
// Arrange the stub.
SClassUnderTest stub = new SClassUnderTest();
stub.InstanceBehavior = BehavedBehaviors.NotImplemented;
stub.MethodToTest01 = () =>
{
baseMethodCall(stub);
};
// Act.
stub.MethodToTest();
}