【问题标题】:How to mock GetType() method in NMock如何在 NMock 中模拟 GetType() 方法
【发布时间】:2009-07-22 10:32:55
【问题描述】:

我有一些生产代码,比如

private bool IsTypeEqual(object theFirstObject, object theSecondObject)
{
       if(theFirstObject.GetType()==theSecondObject.GetType())
       {
               return true;
       }
       else
       {
                return false;
       }
}

现在我必须为此代码编写单元测试用例。我正在使用 NMock 创建 目的。因此,当我传递两个不同类的对象时,它应该转到其他部分。 但实际上,因为我正在模拟这两个对象,所以 GetType() 返回两个对象的 MockObject 类型。我该如何解决这个问题。

【问题讨论】:

  • 这与你为什么不直接返回 (theFirstObject.GetType() == theSecondObject.GetType()) 的问题没有任何关系
  • 你不能模拟一个“对象”。它不是接口或抽象类。

标签: c# unit-testing nmock


【解决方案1】:

您不需要模拟“theFirstObject”或“theSecondObject”。你真的不在乎这些类会发生什么,你只需要断言结果是正确的。

如果我是你,我会传入不同的类型并断言它是真/假:

Assert.AreEqual(false, IsTypeEqual("HelloWorld", 192));

Assert.AreEqual(true, IsTypeEqual("Hello", "World"));

【讨论】:

    【解决方案2】:

    希望这段代码对你有所帮助。

    private bool IsTypeEqual<TMockedType>(object theFirstObject, object theSecondObject)
    {
        Matcher matcher = Is.TypeOf(typeof(TMockedType));
    
        return matcher.Matches(theFirstObject) && matcher.Matches(theSecondObject);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 2015-08-23
      • 2011-02-18
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      相关资源
      最近更新 更多