N
N
Nikita072021-07-19 13:52:54
C++ / C#
Nikita07, 2021-07-19 13:52:54

How to test a class that depends on ILogger and IHttpClientFactory?

Hello everyone, I have the following code

public class RtbService : IRtbService
    {
        private readonly HttpClient _client;
        private readonly ILogger<RtbService> _logger;

        SelectingСounter selectingСounter = new SelectingСounter();

        public RtbService(IHttpClientFactory client, ILogger<RtbService> logger)
        {
            _client = client.CreateClient();
            _logger = logger;
        }

        public async Task<AuctionRequest?> ProcessBidRequest(BidRequestModel requestModel, string endpoint, string protocol, int Identification)
        {
           // Код метода
        }
    }


it is necessary to test the ProcessBidRequest() method, as I understand it, it is necessary to create an object of the RtbService class, then execute the method and compare the results using Assert, but how to create a object if it takes IHttpClientFactory and ILogger as pairs ??
Or is there a way to do this with mock objects?

I use XUnit and Moq

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-07-19
@vabka

NullLogger can be passed as ILogger.
And as IHttpClientFactory, you can pass a real factory, or you can lock it so that it returns and creates an HttpClient with a custom HttpRequestHandler that does not send real requests.
https://anthonygiretti.com/2018/09/06/how-to-unit-...

I
Ilya, 2021-07-19
@sarapinit

Yes, with Moq you can.
For a logger:
var mockLogger = new Mock>();
it is not necessary to configure
for IHttpClientFactory is more difficult. You need to mock the IHttpHandler
and mock the IHttpClientFactory so that the CreateClient method returns new HttpClient(httpHandlerMock.Object);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question