首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试Refit实现的接口时的NullReferenceException

测试Refit实现的接口时的NullReferenceException
EN

Stack Overflow用户
提问于 2021-09-21 09:49:55
回答 1查看 324关注 0票数 1

我正在尝试测试一些错误响应(BadRequest,未授权,...)使用Refit等,我实现了一个返回任何所需响应的TestHandler。使用"OK“(HTTP状态代码200)响应时,响应可以正常工作:

代码语言:javascript
复制
public class Program
{
    private static async Task Main()
    {
        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));
    }
}

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

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);
}

但是,每当我将响应状态代码更改为(例如) BadRequest (400)、NotFound (404)或未授权(401) Refit时,都会抛出NullReferenceException

代码语言:javascript
复制
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

这指向RefitSettings.cs line 183。但我不明白为什么200OK可以工作,而其他任何响应都不行?我做错了什么?

编辑:为了进一步调试,我克隆了Refit,并用Refit NuGet包替换了对Refit项目的项目引用。这会产生一个InvalidOperationException: ITest doesn't look like a Refit interface. Make sure it has at least one method with a Refit HTTP method attribute and Refit is installed in the project。此外,返回几个版本(我已经转到5.2.4)也没有帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-22 12:44:10

在同事的帮助下找到了!事实证明HttpResponseMessage需要一些/任何RequestMessage

变化

代码语言:javascript
复制
public TestHandler(HttpStatusCode httpStatusCode)
    => _response = new HttpResponseMessage(httpStatusCode)
    { 
        Content = new StringContent("Yay!") 
    };

至:

代码语言:javascript
复制
public TestHandler(HttpStatusCode httpStatusCode)
    => _response = new HttpResponseMessage(httpStatusCode)
    {
        RequestMessage = new(),  // <-- This one here...
        Content = new StringContent("Yay!")
    };

它的工作方式和预期的一样。正如问题(和评论)中所说,我很接近,但显然是半睡半醒,因为这正是它指向我的地方。

我已经提交了一个问题here

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69266814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档