Trying to mock a service with an HTTPClient

1 Answer 94 Views
API
Shreyans
Top achievements
Rank 1
Shreyans asked on 11 Jun 2024, 06:07 PM

Hello,

I am currently trying to mock a service I have set up (let's call it ObjectService). It's fairly straightforward - I'm just trying to verify the user is authenticated, and then the response will return an object. This is roughly what it looks like:

private Object _object;

public virtual async Task<Object> GetObject(string token,string url)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    var response = await client.GetStringAsync(url);
    client.Dispose();
    _object = JsonConvert.DeserializeObject<Object>(response);
    
    return _object;
}
I'm running into issues trying to use JustMock to mock this service.  What would be the best way for me to write a unit test for this? 

1 Answer, 1 is accepted

Sort by
0
Ivo
Telerik team
answered on 14 Jun 2024, 03:22 PM

Hello Shreyans,

I am sending a sample code that can be used for verification the value returned from the service. The unit test completely mocks the HTTP client, so the I am afraid that the authentication has to be verified in a different way using the real client and service. Here is a code:

[TestMethod]
public async Task GetObjectTest()
{
    // Aarrange
    var mockHttpService = Mock.Create<HttpClient>();
    var mockResponse =
        "{" +
        "   \"foo\":{" +
        "       \"id\": 10," +
        "       \"name\": \"bar\"" +
        "   }" +
        "}";

    var token = "secret";
    var url = "https://objectservice.org";

    Mock.Arrange(() => mockHttpService.GetStringAsync(url))
        .IgnoreInstance()
        .ReturnsAsync(mockResponse);
    Mock.Arrange(() => new AuthenticationHeaderValue("Bearer", token))
        .CallOriginal();
    Mock.SetupStatic(typeof(JsonConvert));

    // Act
    var sut = new ObjectService();
    var actual = await sut.GetObject(token, url);

    // Assert
    // TODO: verify the actual result from ObjectService.GetObject method call
    Mock.Assert(mockHttpService);
    Mock.Assert(() => JsonConvert.DeserializeObject<object>(mockResponse), Occurs.Once());
}

I hope the provided sample helps. Please let me know if you need further assistance.

Regards,
Ivo
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
API
Asked by
Shreyans
Top achievements
Rank 1
Answers by
Ivo
Telerik team
Share this question
or