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
CodePudding user response:
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.