【问题标题】:How to divert "non public" method in public class moles如何在公共类痣中转移“非公共”方法
【发布时间】:2011-07-24 12:34:05
【问题描述】:

我有一个公共方法,它使用本地私有方法从数据库中获取数据。

private string SomeMethod(string) { ... Doing some operations ... string data = GetDBData(string); Doing some operations ... }

我想使用 moles 转移/隔离私有方法 GetDBData(string),这样我的测试就不需要 DB。

显然,我的问题是:怎么做? 谢谢你 尿素

编辑
附加信息:

我尝试将方法访问器更改为公共和内部保护, 在这两种情况下,我现在都可以将这些方法视为痣。 但是在运行测试时,仍然使用原始方法,而不是我在 PexMethod 中实现的弯路。

【问题讨论】:

    标签: unit-testing moles pex


    【解决方案1】:

    您可以尝试以下任何一种方法。

    • 制作方法internal并在程序集中添加这样的属性:

      [assembly: InternalsVisibleTo("<corresponding-moles-assembly-name>")]

    • 将方法访问更改为受保护的虚拟,然后使用存根。

    • 重构您的类,使其获得一个接口 (IDataAccessObject) 作为构造函数参数,SomeMethod 是该接口的方法之一,然后将该接口的存根在测试方法中传递给您的类。

    【讨论】:

      【解决方案2】:

      我想通了

      如果我有 public MyClass 和 private SomeMethod

      public class MyClass
      {
          private string SomeMethod(string str){}
      }
      

      如果你想mole SomeMethod方法你需要在测试方法中使用AllInstances:

      [PexMethod]
      SomeMethod(string str)
      {
          MMyClass.AllInstances.SomeMethod = (instance, str) => { return "A return string"; };
      }
      
      • 请注意,lambda 接收一个实例参数作为第一个参数。我不确定它的功能是什么。

      【讨论】:

      • instance 参数允许您使用委托中的原始调用实例。
      猜你喜欢
      • 2011-01-30
      • 2015-12-17
      • 2018-09-27
      • 2020-03-27
      • 1970-01-01
      • 2020-03-18
      • 2020-09-22
      • 2019-06-24
      • 2011-03-04
      相关资源
      最近更新 更多