AspNet 核心集成测试 - MethodNotAllowed 响应

我创建了一个带有 GET、POST、PUT 路由的 webapi 项目,这些路由在邮递员中运行良好。但是当我进行集成测试时,只有 GET 和 POST 路由通过。在集成测试中发出 PUT 请求时,它会抛出 MethodNotAllowed Error (405 - Method not allowed)。


系统:Ubuntu 18.10 dotnet 版本:2.2.100


任何建议/方向将不胜感激。


namespace TestingMvc.Tests {

public class JsonContent : StringContent {

    public JsonContent (object obj):

        base (JsonConvert.SerializeObject (obj), Encoding.UTF8, "application/json") { }

}


public class MyTest : IClassFixture<WebApplicationFactory<WebApi.Startup>> {

    private readonly WebApplicationFactory<WebApi.Startup> _factory;


    public MyTest (WebApplicationFactory<WebApi.Startup> factory) {

        _factory = factory;

    }


    // This is Ok -> Returns 200

    [Fact]

    public async Task Get_Attachments () {

        var client = _factory.CreateClient ();

        var response = await client.GetAsync ("/attachments");

        Assert.Equal (HttpStatusCode.OK, response.StatusCode);

    }


    // This is Ok -> returns 200

    [Fact]

    public async Task Post_Attachments () {

        var client = _factory.CreateClient ();

        var response = await client.PostAsync ("/attachments", new JsonContent(new { a = "foobaz" }));

        Assert.Equal (HttpStatusCode.OK, response.StatusCode);

    }


    // This is not ok -> returns 405 Method not allowed

    [Fact]

    public async Task Put_Attachments () {

        var client = _factory.CreateClient ();

        var response = await client.PutAsync ("/attachments", new JsonContent(new { a = "foobaz" }));

        Assert.Equal (HttpStatusCode.OK, response.StatusCode);

    }

}

}

当年话下
浏览 115回答 2
2回答

慕盖茨4494581

我忘了发布我的控制器。&nbsp; &nbsp; // PUT Attachments/someguid&nbsp; &nbsp; [HttpPut ("{id}")]&nbsp; &nbsp; public ActionResult<AttachmentDto> Put (Guid id, [FromBody] AttachmentDto attachment) {&nbsp; &nbsp; &nbsp; &nbsp; return Ok (_attachmentService.CreateOrUpdate (id, attachment));&nbsp; &nbsp; }因此,为该操作定义了一个 ID 参数,但在集成测试中它丢失了。它应该是:var response = await client.PutAsync ("/attachments/01D7ACA3-575C-4E60-859F-DB95B70F8190", ...这解决了我的问题。

忽然笑

您是否将 Postman 通过的 Header 与您的测试构建的 Header 进行了比较?我可以看到的一件事可能是问题是您没有发送内容类型。ContentType = "文本/json"
打开App,查看更多内容
随时随地看视频慕课网APP