用Moq实例化模拟是非常缓慢的

时间:2015-11-27 22:54:01

标签: c# unit-testing moq

测试中的方法接受cell_providerFunc<string, Cell>,创建625个Cell类实例,并在每个实例上调用instantiate(Vector2)

测试中有3个方法调用,所以cell_provider完全被称为1875次

使用此测试Func<string, Cell> 0.2s

中完成
class DummyCell : Cell
{
    public DummyCell(string s):base(s)
    {
    }
    public Action<Vector2> on_instantiated;
    public override void instantiate(Vector2 position)
    {
        if (on_instantiated != null)
        {
            on_instantiated.Invoke(position);
        }
    }
    public override void destroy()
    {
    }
}
//...
Func<string, Cell> cell_provider = s =>
    {
      DummyCell res = new DummyCell(s);
      res.on_instantiated += v =>
       {
           min_x = min(min_x, v.x);
           max_x = max(max_x, v.x);
           min_y = min(min_y, v.y);
           max_y = max(max_y, v.y);
       };
      return res;
    };

这在 10秒

中完成
Func<string, Cell> cell_provider = s =>
  {
      Mock<Cell> res = new Mock<Cell>(s);
      res.Setup(c => c.instantiate(It.IsAny<Vector2>()))
      .Callback<Vector2>(v =>
        {
            min_x = min(min_x, v.x);
            max_x = max(max_x, v.x);
            min_y = min(min_y, v.y);
            max_y = max(max_y, v.y);
        });
      return res.Object;
  };

我想,这是因为我不仅在cell_provider中创建了一个Mock<Cell>实例,还使用了Setup

我能写这样的东西吗?

Mock<Cell> res = new Mock<Cell>(<I should put something here>);
res.Setup(c => c.instantiate(It.IsAny<Vector2>()))
  .Callback<Vector2>(v =>
    {
        min_x = min(min_x, v.x);
        max_x = max(max_x, v.x);
        min_y = min(min_y, v.y);
        max_y = max(max_y, v.y);
    });
Func<string, Cell> cell_provider = s =>
  {
      return res.<make_instance>(s);
  };

0 个答案:

没有答案