vendredi 27 novembre 2015

Instantiating mocks with Moq is insanely slow

Method under tests accepts cell_provider which is Func<string, Cell>, creates 625 instances of Cell class and calls instantiate(Vector2) on each instance.

There are 3 calls to the method inside the test, so cell_provider is totally called 1875 times

Test with this this Func<string, Cell> completes in 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;
    };

This completes in 10 seconds

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;
  };

I guess, it's because, I not only create a Mock<Cell> instance inside cell_provider, but also use Setup

Can I write something like this?

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);
  };

Aucun commentaire:

Enregistrer un commentaire