【问题标题】:Is Moq incompatible with PrivateObject?起订量与 PrivateObject 不兼容吗?
【发布时间】:2014-01-24 11:50:18
【问题描述】:

我正在尝试在模拟对象上测试私有方法。请冷静下来,我知道你要把你的干草叉拿出来。

我很清楚要说的一切都可以通过对我大喊 REFACTOR 来回答。我只需要一个直接的答案。有人看着我的眼睛告诉我这是不可能的。这是一个无法通过谷歌搜索的问题,所以我只需要听到它。

这就是我正在处理的问题。

public class SecretManager
{
   protected virtual string AwfulString { get { return "AWFUL, AWFUL THING"; }

   public SecretManager()
   {
      //do something awful that should be done using injection
   }

   private string RevealSecretMessage()
   {
      return "don't forget to drink your ovaltine";
   }
}

我正在尝试测试它。

var mgr = new Mock<SecretManager>();
mgr.Protected().SetupGet<string>("AwfulThing").Returns("");

var privateObj = new PrivateObject(mgr.Object);
string secretmsg = privateObj.Invoke("RevealSecretMessage");

Assert.IsTrue(secretmsg.Contains("ovaltine"));

还有例外:

System.MissingMethodException: Method 'Castle.Proxies.SecretManagerProxy.RevealSecretMessage' not found

我正在尝试做的事,虽然很疯狂,可能吗?或者这只是单元测试无法承受的狂妄自大?

【问题讨论】:

    标签: c# moq vs-unit-testing-framework privateobject.invoke


    【解决方案1】:

    您正在尝试调用 Castle 创建的代理上的方法。代理将无法访问它继承自的类的私有方法,因为该方法是私有的。请记住,Castle.Proxies.SecretManagerProxy 实际上是 SecretManager 的子类。

    您真的需要模拟 SecretManager 吗?我意识到您的代码是真实代码的精简摘要,但似乎您对模拟所做的唯一事情就是为您尝试测试的方法未使用的属性设置返回值.

    【讨论】:

      【解决方案2】:
      var privateObj = new PrivateObject(mgr.Object, new PrivateType(typeof(SecretManager)));
      string secretmsg = privateObj.Invoke("RevealSecretMessage");
      

      它可以通过为PrivateObject 指定PrivateType 来工作。

      【讨论】:

        【解决方案3】:

        您的代码应该遵循您要测试的内容。您不需要模拟 SecretManager 和 SetGet "AwfulThing",因为您没有使用它。

        var privateObj = new PrivateObject(new SecretManager());
        string secretmsg = (string)privateObj.Invoke("RevealSecretMessage", new object[] {     });
        
        Assert.IsTrue(secretmsg.Contains("ovaltine"));
        

        但理想情况下,您不应该测试私有方法。解释见下文:

        http://lassekoskela.com/thoughts/24/test-everything-but-not-private-methods/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-16
          • 1970-01-01
          • 1970-01-01
          • 2019-03-17
          • 2012-02-11
          • 1970-01-01
          • 1970-01-01
          • 2015-08-09
          相关资源
          最近更新 更多