kelvin sand
kelvin sand

Reputation: 503

How to mock a return of method call internal a other method

I would like to know if it is possible to mock the return of a method of a class that is instantiated within the target test method. The different point here is that to instantiate this object, it is necessary to pass in its constructor an object returned from a static class. Follow the example to be clearer.

public async Task Invoke(HttpContext httpContext)
{
    GrpcChannel channel = GrpcChannel.ForAddress("address");
    var client = new MethodDescriptorCaller(channel);
    client.CallGrpcAsync(); //I need to mock the return of this method
}

The idea I had so far would be to encapsulate this process in another class. And using dependency injection to mock that return. But, I believe it is a very bad solution.

Upvotes: 0

Views: 206

Answers (1)

jjchiw
jjchiw

Reputation: 4445

I don't think that creating a factory and inject it, it's a bad solution at all IMO

I think something like this should it...

interface IMethodDescriptorCallerFactory
{
  MethodDescriptorCaller Build(GrpcChannel channel);
}

class MethodDescriptorCallerFactory : IMethodDescriptorCallerFactory
{
  MethodDescriptorCaller Build(GrpcChannel channel)
  {
    return new MethodDescriptorCaller(channel);
  }
}

class Foo
{
  IMethodDescriptorCallerFactory _methodDescriptorCallerFactory;

  public Foo(IMethodDescriptorCallerFactory methodDescriptorCallerFactory)
  {
    _methodDescriptorCallerFactory = methodDescriptorCallerFactory
  }

  public async Task Invoke(HttpContext httpContext)
  {
      GrpcChannel channel = GrpcChannel.ForAddress("address");
      var client = _methodDescriptorCallerFactory.Build(channel);
      client.CallGrpcAsync(); //I need to mock the return of this method
  }
}


class FooTest
{
  [Fact]
  public async Task Test_Invoke()
  {
    var methodDescriptorCaller = Mock.Of<MethodDescriptorCaller>(m =>
        m.CallGrpcAsync() == Task.Completed
    );

    var methodDescriptorCallerFactory = Mock.Of<IMethodDescriptorCallerFactory>(m =>
        m.Build(It.IsAny<GrpcChannel>()) == methodDescriptorCaller
    );

    var foo = new Foo(methodDescriptorCallerFactory);

    var httpContext = Mock.Of<HttpContext>();

    await foo.Invoke(httpContext);

    Mock.Get(methodDescriptorCallerFactory).VerifyAll();
    Mock.Get(methodDescriptorCaller).VerifyAll();
  }
}

Upvotes: 1

Related Questions