简体   繁体   English

我应该创建一个接口并模拟此类吗

[英]Should I create a interface and mock this class

I have this class called Table: 我有一个叫做Table的类:

class Table
{
    public string Name
    {
        get
        {
            return this.wrapper.Eval(//some command); 
            //wrapper is pass in by the ctor and is a COM object.
        }
    }
}

which is used in this class: 在此类中使用:

class Map
{
  public Map MapTable(Table table)
  {
     return new Map(table.Name);
  }
}

I want to test MapTable command, should I be mocking Table or should I mock the wrapper object that is used by the table object. 我想测试MapTable命令,应该模拟表还是模拟表对象使用的包装器对象。

I was thinking something like this 我在想这样的事情

 Test()
 {
   Mock<ITable> mocktable = new Mock<ITable>(//pass in the wrapper object);
   mocktable.ExpectGet(n => n.Name).Returns("Hello World");

   ITable table = mocktable.object;
   Map mymap = Map.MapTable(table);
 }

Would that be correct? 正确吗?

Beyond the fact that there is usually no one perfect testing solution, I'd first go for mocking the COM object: there should be a interface available and you'll probably want to test everything "above" it. 除了通常没有一个完美的测试解决方案这一事实之外,我首先会模拟COM对象:应该有一个可用的接口,并且您可能想测试“上面”的所有内容。

If the Table contains non-trivial code (eg within the Eval() ; anything with conditionals; or eg parsing using a Culture ) you might want to have a mock of it as you show in your example. 如果Table包含非平凡的代码(例如,在Eval() ;带有条件的任何内容;或例如,使用Culture解析),则可能需要对它进行模拟,如示例所示。

Yes your sample looks fine, if you want to test the Map object you should be mocking the Table object. 是的,您的示例看起来不错,如果您想测试Map对象,则应该模拟Table对象。

If you do it the other way around you will not test the Map constructor. 如果以其他方式进行操作,则不会测试Map构造函数。

To help me understand. 为了帮助我理解。 It looks like you just want the name from the Table, not the Table itself. 看起来您只需要表中的名称,而不是表本身。 In that case, why not just pass in a name and leave the Table out of it? 在这种情况下,为什么不只是传入一个名称,而忽略表呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM