0

我正在使用 Microsoft Moles,并对以下主题感到好奇:

  • 有什么方法可以设置类型的行为(例如未实现),但保留单个特定方法的原始行为?

我的意图是将要测试的方法(不知道从要测试的方法调用的方法)与其类完全隔离。


以下代码对我不起作用,因为 moles 已完全禁用,并且任何使用的子方法都使用其原始行为:

MBaseObjectType.BehaveAsNotImplemented();
MolesContext.ExecuteWithoutMoles(() => mBaseObject.MethodToTest())
4

2 回答 2

0

可以为所有或特定的 Mole 实例保留原始行为。Fallthrough 行为为未注册的方法禁用 Moles。

// All instances:
MFileWatcher.Behavior = MoleBehaviors.Fallthrough;

// Specific instance
var original = new BaseObjectType(null);
var moledInstance = new MBaseObjectType(original) { InstanceBehavior = MoleBehaviors.Fallthrough };

参考:http ://social.msdn.microsoft.com/Forums/en-US/pex/thread/39af5a02-1cc9-4cf3-a254-3bdc923175db

于 2011-06-08T17:59:04.357 回答
0

我猜你只能使用存根来实现这种行为。

这是一个代码示例。我们将调用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();
}
于 2011-06-07T19:18:15.080 回答