AlexanderM
AlexanderM

Reputation: 1683

Mocking the api client generated by Swagger Codegen

I generated the C# client using swagger-codegen. Currently I am writing a wrapper around that client and would like to have unit tests around my logic. However I am trying to figure out how can I mock the calls to the generated clients. I am using a Moq framework. I am trying to use the code from How to mock RestSharp portable library in Unit Test to mock the RestClient. However I am unable to figure out how to inject RestClient into the generated client.

Upvotes: 1

Views: 2031

Answers (1)

Oscar Fraxedas
Oscar Fraxedas

Reputation: 4667

The generated swagger client will be a partial class.
Add a partial class for the client and extract the method you want to mock.
Let's assume you want to Mock the Get by id method.

public interface IApiClient
{
    Task<Item> GetItemByIdAsync(int id);
}

public partial class swaggerClient: IApiClient
{
    
}

On your test code you'll have to mock using the interface:

var mock= new Mock<IApiClient>();
mock.Setup(r => r.GetItemByIdAsync(It.IsAny<int>()))
      .ReturnsAsync((int id) => new Item(id));
var client = mock.Object;

Happy testing!

Upvotes: 3

Related Questions