0

I am trying to Moq this method below. How would I moq a method with a Generic Class T? Below is method and currently attemping solution,

Method:

    public async Task<TV> HttpPost<T, TV>(string url, T prm, string accessToken = null)
    {
        try
        {
            if ((accessToken ?? "").Length > 0)
                _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            using (var result = await _client.PostAsJsonAsync(url, prm))
            {
                result.EnsureSuccessStatusCode();
                using (var content = result.Content)
                {
                    var ret = await content.ReadAsJsonAsync<TV>();
                    return ret;
                }
            }
        }
        catch (Exception ex)
        {
            var message = $"Url: {url}, Data: {JsonConvert.SerializeObject(prm)}";
            ex.Data["Url"] = message;
            throw;
        }
    }

Attempt:

        var mock = new Mock<HttpDataLayerUtilsAsync>();
        mock.Setup(b => b.HttpPost(It.IsAny<string>, It.IsAny <CustomDataModelRequest>).Returns..

Resource:

Mocking generic method call for any given type parameter

1 Answers1

1

You need to supply the generic arguments to the HttpPost in the Setup, for example:

//                           T                         TV
.Setup(b => b.HttpPost<CustomDataModelRequest, CustomDataModelResponse>(
  It.IsAny<string>(), 
  It.IsAny<CustomDataModelRequest>(), 
  null))

As well as passing a value for the optional parameter.

For the Return you can use:

.ReturnsAsync(new CustomDataModelResponse());

Then you can call it like so:

var result = await mock.Object.HttpPost<CustomDataModelRequest, CustomDataModelResponse>("", new CustomDataModelRequest(), "");
DaveShaw
  • 52,123
  • 16
  • 112
  • 141