Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test the Refit ApiResponse<T>?

I'm using refit to call APIs and the response is wrapped in ApiResonse<T>. I can mock the refit call that returns a mocked ApiResponse<T> and assert. Everything works as it should except I'm not sure how I can test the api call that returns an exception.

[Get("/customer/{id}")]
Task<ApiResponse<Customer>> GetCustomer(int id);

It seems if ApiResponse<T> is used Refit wraps all the exceptions that happens inside the request into ApiException and attaches to ApiResponse<T>. If Task<T> is used instead, catching the ApiException is the responsibility of the caller.

I created the ApiException with ApiException.Create() but not sure where to put that in the ApiResponse<T>. The last parameter to the Create() method is ApiException but the exception I create and set doesn't show up in the ApiResponse at all and therefore can't test.

var apiResponse = new ApiResponse<Customer>(
    new HttpResponseMessage(BadRequest),
    null,
    null,
    await ApiException.Create(,,,Exception("Something bad happened inside the api")
 );

I can't get the Something bad happened... message in the unit test but just the 'Bad Request' message. Am I unit testing the ApiResponse in refit right? Any help is greatly appreciated. Thanks

like image 203
Stack Undefined Avatar asked Dec 06 '25 17:12

Stack Undefined


1 Answers

I don't know Refit, but according to their docs I'd expect the following two options:

Return ApiResponse<Customer>

Let's take a look at your code (which is not correct C#, by the way - please provide correctly working code):

var apiResponse = new ApiResponse<Customer>(
    new HttpResponseMessage(BadRequest),
    null,
    null,
    await ApiException.Create(,,,Exception("Something bad happened inside the api")
 );

When executing this code, Refit is instructed to return exactly what you ask for: return HTTP 500 with the following inner exception.

So I'd expect you'll find Something bad happened inside the api inside apiResponse.Error, but no exception will be thrown.

Throw ApiException

Since ApiException derives from System.Exception, you can replace this

var apiResponse = new ApiResponse<Customer>(
    new HttpResponseMessage(BadRequest),
    null,
    null,
    await ApiException.Create(,,,Exception("Something bad happened inside the api")
 );

by

throw await ApiException.Create("Something bad happened inside the api", message, method, response, settings);

Now you can catch your exception inside your unit test.

like image 196
mu88 Avatar answered Dec 08 '25 05:12

mu88



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!