【问题标题】:Mock call to protected method of base abstract class from derived class public method using Microsoft.fakes使用 Microsoft.fakes 从派生类公共方法模拟调用基抽象类的受保护方法
【发布时间】:2017-05-05 13:42:39
【问题描述】:

我正在尝试使用 Microsoft.Fakes 为下面显示的代码编写单元测试。

作为 Microsoft.Fakes 的新手,我在模拟对抽象基类受保护功能方法的调用时遇到了困难

我的基类:

public abstract class MyAbstractBaseClass
{
protected virtual int MyFunctionalBaseClassMethod(int parameter1)
{
return (parameter1 * parameter1);
}
}  

我的孩子班:

public class MyChildClass : MyAbstractBaseClass
{
public int GetSquare(int parameter1) //(target method for unit test)
{
return MyFunctionalBaseClassMethod(parameter1); //(target method to mock using Fakes)
}
} 

我尝试使用以下单元测试代码进行模拟,但没有成功:

var square = 10;
var stubMyAbstractBaseClass = new Fakes.StubMyAbstractBase()
{
MyFunctionalBaseClassMethod = (a) => { return square; }
};  

注意:我的抽象基类受保护方法执行复杂的操作,所以我需要模拟它。上面的代码只是一个示例。

任何指针将不胜感激!

【问题讨论】:

  • 如果你的目标是 GetSquare() 为什么你不能做类似 var x = _myChildClass.GetSquare(2);然后就可以 Assert.IsEqual(2, x);
  • 如前所述请注意:我的抽象基类受保护方法执行复杂的操作,因此我需要模拟它。上面的代码只是一个示例。

标签: c# unit-testing protected microsoft-fakes abstract-base-class


【解决方案1】:

您需要存根 MyChildClass 而不是抽象类。这对我有用。

[TestMethod]
public void CheckAbstractClassStub()
{
    var myChild = new StubMyChildClass()
    {
        MyFunctionalBaseClassMethodInt32 = (num) => { return 49; }
    };

    int result = myChild.GetSquare(5);
    Assert.AreEqual(result, 49);
}

编辑:是的,它受到保护。正如我上面提到的,您需要在派生类MyChildClass 中存根受保护的方法。您已经删除了抽象类,那里没有实例,它不会被调用。如果您想在所有情况下都这样做,您也许可以使用 Shims,但此时您只会让它变得更加困难。

这是我的基类和子类,以便您进行比较。

public abstract class MyAbstractBaseClass
{
    protected virtual int MyFunctionalBaseClassMethod(int parameter1)
    {
        return (parameter1 * parameter1);
    }
}

public class MyChildClass : MyAbstractBaseClass
{
    public int GetSquare(int parameter1) //(target method for unit test)
    {
        return MyFunctionalBaseClassMethod(parameter1); //(target method to mock using Fakes)
    }
}

这是在调试点停止的代码的屏幕截图

【讨论】:

  • 'MyFunctionalBaseClassMethodInt32 = (num) => { return 49; }' 在我的情况下不起作用,基类方法不是公共的受保护的。
猜你喜欢
  • 2015-08-02
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
相关资源
最近更新 更多