Nil Pun
Nil Pun

Reputation: 17373

MOQ: mock the interface?

How can I mock the interface below?

interface IServiceClientAPI
    {

        ResponseData GetData(string userid,string orderid);
    }

Upvotes: 0

Views: 279

Answers (1)

Huske
Huske

Reputation: 9296

You could mock your interface like following:

[TestMethod]
public void SomeMethod_SomeScenarioWhichYourAreTesting_ExpectedResult()
{
    // Arrange
    var mockServiceClientApi = new Mock<IServiceClientAPI>();
    var responseData = new ResponseData(); // Add any necessary initialization to this member
    mockServiceClientApi.Setup(m => m.GetData(It.IsAny<string>(), It.IsAny<string>()).Returns(responseData).Verifiable();

    var someObject = new SomeObject(mockServiceClientApi.Object);

    // Act
    var result = someObject.DoSomething();

    // Assert
    mockServiceClientApi.Verify();
}

In the above code I wrote a test method (which would work with MSTest). Basically you first need to prepare your mocked object and setup any method which you expect your methods to call.

It can be pretty strange to program with mocking tools at the beginning, but once you get a hang of it you will see how valuable it can be. You should first try to understand unit testing and then you will have a better picture about mocking API's. For that I would suggest you have a look at The Art of Unit Testing by Roy Osherove.

That's about it. Regards.

Upvotes: 1

Related Questions