Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG?] NullReferenceException when testing API implemented by Refit #1243

Open
RobThree opened this issue Sep 22, 2021 · 2 comments
Open

[BUG?] NullReferenceException when testing API implemented by Refit #1243

RobThree opened this issue Sep 22, 2021 · 2 comments
Labels

Comments

@RobThree
Copy link

I'm not sure if this is by-design or a bug, but I ran into an issue recently and thought I'd report it.

For reference: I have discussed this on stackoverflow question.

I was unittesting some REST API code and implemented a test-HttpMessageHandler to be able to return any desired (json/html/whatever) response and statuscode (200 OK, 401 Unauthorized, ...). This is the handler in simplified form:

public class TestHandler : HttpMessageHandler
{
    private readonly HttpResponseMessage _response;

    public TestHandler(HttpStatusCode httpStatusCode)
        => _response = new HttpResponseMessage(httpStatusCode) {
                Content = new StringContent("Yay!")
        };

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        => Task.FromResult(_response);
}

Then a Refit interface:

public interface ITest
{
    [Get("/foo/{bar}")]
    Task<string> Test(string bar);
}

Finally, a "test":

var api = RestService.For<ITest>(
  new HttpClient(new TestHandler(HttpStatusCode.OK))
      {
          BaseAddress = new Uri("https://example.com")
      }
  );
  Console.WriteLine(await api.Test("foo").ConfigureAwait(false));

This works fine; however, whenever I tried anything other than an OK result I got a NullReference exception.

Object reference not set to an instance of an object.
   at Refit.DefaultApiExceptionFactory.<CreateExceptionAsync>d__4.MoveNext() in /_/Refit/RefitSettings.cs:line 183
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Refit.RequestBuilderImplementation.<>c__DisplayClass14_0`2.<<BuildCancellableTaskFuncForMethod>b__0>d.MoveNext() in /_/Refit/RequestBuilderImplementation.cs:line 313
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at RefitTest.Program.<Main>d__0.MoveNext() in C:\Users\Rob\Source\Repos\RefitTest\RefitTest\Program.cs:line 18

Long story short: I finally found it: the returned HttpResponseMessage needs a RequestMessage:

    public TestHandler(HttpStatusCode httpStatusCode)
        => _response = new HttpResponseMessage(httpStatusCode) {
                RequestMessage = new(),  // <-- This one here...
                Content = new StringContent("Yay!")
        };

Again: I'm not sure if this is a bug, but we tracked it down to this line, where RequestMessage is null obviously. If anything, maybe a more explicit null check and more specific exception could be thrown?

@RobThree RobThree added the bug label Sep 22, 2021
@clairernovotny
Copy link
Member

@RobThree I believe the built in protocol handlers always provide the incoming request message in the response. I'm not 100% sure of the usage contract in the API, but I've never seen it otherwise.

Rather than a code fix, I'd suggest a documentation update to clarify this. Would you mind submitting a PR to mention that in the docs in the right spot?

@RobThree
Copy link
Author

I don't mind at all. However, what docs are you referring to? The README.md? Those are all the docs I'm aware of? And I can't really find a good place to add it in the (current) docs. There's no explicit unittesting or messagehandling section so I'd have to mention it somewhere as an aside?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants