user3177615
user3177615

Reputation: 25

Using moq for service within a service

I have a testing question using Moq. I've looked at the other moq answers here but I don't understand moq well enough to be able to judge if they answer my question.

Here is the code background: I have a service 'MyService' and I need to make a call on a method 'MyMethod'.

var response = myServ.MyMethod(request);

MyService is constructor injected with multiple external services. I also have a public interface for this class.

 public MyService(IExternalService1 serv1, 
         IExternalService2 serv2, 
         IExternalService3 serv3, 
         IExternalService4 serv4)
{
    _serv1 = serv1;
    _serv2 = serv2;
    _serv3 = serv3;
    _serv4 = serv4;
}

Now MyMethod makes a call on one of those external services. Quick definition of MyRequest and MyResponse below.

public class MyRequest()
{
    public int inId { get; set; }
}
public class MyResponse()
{
    public int outId { get; set; }
}

So the implementation of MyMethod is:

public MyResponse MyMethod(request)
{
    return _serv3.DoSomething(request);
}

The function above returns a new object of MyResponse and sets the value of outId to a value.

Now for the test:

public void ShouldReturnValidOutId()
{

 var myService = new Mock<IMyService>();
 myService.Setup(
            m => m.MyMethod(It.IsAny<MyRequest>())).Returns(new MyResponse() { outId = 5; });

 var request  = new MyRequest() { inId = 100 };
 var response = myService ??? make my call to the MyMethod method ???

 Assert.Equals(response.outId, 5);
}

Now I have 2 questions:

1) How do I make the call to MyMethod?

2) I think that my whole mock setup might be wrong as I don't really want to mock MyService class as that is what I am actually testing but I want to mock _serv3 (IExternalService3). How do I set that up in the .Setup() function.

Any help appreciated.

Thanks

Upvotes: 1

Views: 2093

Answers (1)

BartoszKP
BartoszKP

Reputation: 35911

To test MyService don't mock it - mock its dependencies! Simple example:

var service3Mock = new Mock<IExternalService3>();
service3Mock.Setup(m => m.DoSomething(It.IsAny<MyRequest>()))
    .Returns(new MyResponse() { outId = 5; });

var myService = new MyService(null, null, service3Mock.Object, null);

var request  = new MyRequest() { inId = 100 };
var response = myService.MyMethod(request);

Assert.Equals(response.outId, 5);

Upvotes: 3

Related Questions