gpt4 book ai didi

.net - 使用NUnit与ASP.NET WebApi Controller 执行集成测试

转载 作者:行者123 更新时间:2023-12-04 04:06:48 26 4
gpt4 key购买 nike

我正在尝试使用NUnit设置测试以执行ASP.NET WebApi Controller 的一些集成测试。我发现有几篇文章讨论了使用HttpServer进行内存中托管的方法,这些文章似乎不需要Web服务器来托管所有内容,从而简化了事情。

  • ASP.NET Web API: in-memory hosting
  • ASP.NET Web API integration testing with in-memory hosting

  • 问题是我唯一得到的答复是404-Not Found。

    通过浏览器或Fiddler手动测试时, Controller 正在工作。路径定义是从工作站点复制的。测试项目引用了api项目,并且dll被复制到与测试相同的文件夹中。

    提前致谢。

    这是测试课
    [TestFixture]
    public class InMemoryTests
    {
    private HttpServer Server;
    private string UrlBase = "http://some.server/";

    [TestFixtureSetUp]
    public void Setup()
    {

    var config = new HttpConfiguration();
    config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
    config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

    Server = new HttpServer(config);
    }

    [Test]
    public void GetOrderStatus()
    {
    var client = new HttpClient(Server);
    var request = createRequest("api/Orders/GetOrderStatus?companyCode=001&orderNumber=1234", "application/json", HttpMethod.Get);

    using (HttpResponseMessage response = client.SendAsync(request).Result)
    {
    Assert.IsNotNull(response);
    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    Assert.NotNull(response.Content);
    }
    }

    private HttpRequestMessage createRequest(string url, string mthv, HttpMethod method)
    {
    var request = new HttpRequestMessage();

    request.RequestUri = new Uri(UrlBase + url);
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
    request.Method = method;

    return request;
    }

    private HttpRequestMessage createRequest<T>(string url, string mthv, HttpMethod method, T content, MediaTypeFormatter formatter) where T : class
    {
    HttpRequestMessage request = createRequest(url, mthv, method);
    request.Content = new ObjectContent<T>(content, formatter);

    return request;
    }

    public void Dispose()
    {
    if (Server != null)
    {
    Server.Dispose();
    }
    }
    }

    最佳答案

    当我将测试类移到与 Controller 相同的程序集中时,我也看到了这个问题,似乎消失了。我知道通常不适合进行测试。

    经过一番挖掘后,似乎出现了一个错误,该错误仅在宿主代码中出现,即调用代码没有与 Controller 共享同一程序集,因为它没有设法加载所需的程序集。

    要确认这是您的问题/临时解决方法,请将其添加为测试的第一行:-

    Type myType = typeof(myControllerType);

    更多信息,请访问: http://forums.asp.net/t/1772734.aspx/1

    关于.net - 使用NUnit与ASP.NET WebApi Controller 执行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11676828/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com