使用NUnit与ASP.NET WebApi控制器执行集成测试
发布时间:2020-12-16 04:29:01 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试使用NUnit设置测试来执行ASP.NET WebApi控制器的一些集成测试.我发现有几篇文章讨论使用HttpServer进行内存中托管,这似乎可以通过不需要托管所有内容的Web服务器来简化操作. ASP.NET Web API: in-memory hosting ASP.NET Web API integration test
我正在尝试使用NUnit设置测试来执行ASP.NET WebApi控制器的一些集成测试.我发现有几篇文章讨论使用HttpServer进行内存中托管,这似乎可以通过不需要托管所有内容的Web服务器来简化操作.
> ASP.NET Web API: in-memory hosting 问题是我得到的唯一回应是404-Not Found. 通过浏览器或Fiddler手动测试时,控制器正在工作.路径定义是从工作站点复制的. 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,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(); } } } 解决方法
我也看到了这个问题,当我将测试类移动到与控制器相同的程序集中时,似乎消失了;我知道一般不适合测试.
经过一些挖掘之后,当调用代码与控制器不共享同一个程序集时,只有自身主机才会出现一个错误,因为它没有设法加载所需的程序集. 要确认这是您的问题/暂时解决方法,请将此添加为测试的第一行: – Type myType = typeof(myControllerType); 更多信息:http://forums.asp.net/t/1772734.aspx/1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 当我尝试添加映射文件时,ASP.NET脚手架的问题
- asp.net-mvc-4 – 为什么一些Asp.Net MVC4模板需要System.S
- asp.net – 关于MVC3中助手的清晰度?
- asp.net – 在页面生命周期内保持数据库连接打开是否可以接
- asp.net – 报表查看器控件(Web)显示空白报告
- ASP.NET中App_Data等文件夹的作用
- asp.net – 间歇性SQL连接错误
- asp.net-mvc – 如何将索引应用于IEnumerable表达式类型并在
- asp.net – 有没有= window.onload在Javascript?
- asp.net-mvc-4 – MVC4如何挂钩OnSessionStart事件?
推荐文章
站长推荐
热点阅读