Home > Blockchain >  Mock object created in the constructor
Mock object created in the constructor

Time:10-07

I have a constructor for EdmService that creates an object EdmApiClient in the constructor

public EdmService(IOptions<EdmApiClientOptions> apiOptions, IHttpClientFactory httpClientFactory)
{
    Check.ArgumentIsNotNull(apiOptions, nameof(apiOptions));
    Check.ArgumentIsNotNull(httpClientFactory, nameof(httpClientFactory));
    _client = new EdmApiClient(apiOptions.Value.Hostname, httpClientFactory.CreateClient(nameof(EdmApiClient)));
}

This _client is used in the method that I want to test. But how to mock it?

CodePudding user response:

You cannot mock it if the service creates a new instance. You must change your service to accept all its dependencies via the constructor:

public EdmService(IOptions<EdmApiClientOptions> apiOptions, IHttpClientFactory httpClientFactory, EdmApiClient client)
{
    Check.ArgumentIsNotNull(apiOptions, nameof(apiOptions));
    Check.ArgumentIsNotNull(httpClientFactory, nameof(httpClientFactory));
    _client = client;
}

public static void Main() {
    var svc = new EdmService(
        apiOptions,
        httpClientFactory,
        new EdmApiClient(
            apiOptions.Value.Hostname,
            httpClientFactory.CreateClient(nameof(EdmApiClient)));
}

If passing the client is not an option, consider passing a factory instead.

public EdmService(IOptions<EdmApiClientOptions> apiOptions, IHttpClientFactory httpClientFactory, Func<String, IHttpClient, EdmApiClient> clientFactory)
{
    Check.ArgumentIsNotNull(apiOptions, nameof(apiOptions));
    Check.ArgumentIsNotNull(httpClientFactory, nameof(httpClientFactory));
    _client = client(apiOptions.Value.Hostname, httpClientFactory.CreateClient(nameof(EdmApiClient)));
}

public static void Main() {
    var svc = new EdmService(
        apiOptions,
        httpClientFactory,
        (hostname, client) => new EdmApiClient(hostname, client));
}

Or use the real EdmApiClient, but have your httpClientFactory return a test double.

  • Related