本文介绍了单元测试的ASP.NET Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是单元测试一个简单的POST:
公开的Htt presponseMessage<文件> PostDocument(文档文件)
{
文件= repository.Add(文件); VAR响应=新的Htt presponseMessage<文件>(文件,则httpStatus code.Created); VAR URI = Url.Route(空,新{ID = document.Id}); response.Headers.Location =新的URI(Request.RequestUri,URI); 返回响应;
}
然而,URL和请求显然将成为空。
有没有嘲讽了ControllerContext替代和HttpContext的?
更新:
改成了:
公开的Htt presponseMessage<文件> PostDocument(文档文件,URI位置= NULL)
{
文件= repository.Add(文件); VAR响应=新的Htt presponseMessage<文件>(文件,则httpStatus code.Created); 如果(位置== NULL)
{
VAR URI = Url.Route(空,新{ID = document.Id});
位置=新的URI(Request.RequestUri,URI);
} response.Headers.Location =位置; 返回响应;
}
更新2:
这是更好的:
公开的Htt presponseMessage<文件> PostDocument(文档文件)
{
VAR URI = Url.Route(空,新{ID = document.Id});
VAR的位置=新的URI(Request.RequestUri,URI); 返回PostDocument(文件位置);
}[无为]
公众的Htt presponseMessage<文件> PostDocument(文档文件,URI位置)
{
文件= repository.Add(文件); VAR响应=新的Htt presponseMessage<文件>(文件,则httpStatus code.Created);
response.Headers.Location =位置;
返回响应;
}
解决方案
使用FakeItEasy我得到它的工作在TestInitialize这样做。
this.Controller.ControllerContext =新System.Web.Http.Controllers.HttpControllerContext();
this.Controller.Request = A.Fake< Htt的prequestMessage>();
I'm unit testing a simple post:
public HttpResponseMessage<Document> PostDocument(Document document)
{
document = repository.Add(document);
var response = new HttpResponseMessage<Document>(document, HttpStatusCode.Created);
var uri = Url.Route(null, new { id = document.Id });
response.Headers.Location = new Uri(Request.RequestUri, uri);
return response;
}
However, the 'URL' and 'Request' are obviously going to be null.
Is there an alternative to mocking out ControllerContext and HttpContext?
Update:
Changed it to:
public HttpResponseMessage<Document> PostDocument(Document document,Uri location = null)
{
document = repository.Add(document);
var response = new HttpResponseMessage<Document>(document, HttpStatusCode.Created);
if (location == null)
{
var uri = Url.Route(null, new { id = document.Id });
location = new Uri(Request.RequestUri, uri);
}
response.Headers.Location = location;
return response;
}
Update 2:
This is better:
public HttpResponseMessage<Document> PostDocument(Document document)
{
var uri = Url.Route(null, new { id = document.Id });
var location = new Uri(Request.RequestUri, uri);
return PostDocument(document, location);
}
[NonAction]
public HttpResponseMessage<Document> PostDocument(Document document, Uri location)
{
document = repository.Add(document);
var response = new HttpResponseMessage<Document>(document, HttpStatusCode.Created);
response.Headers.Location = location;
return response;
}
解决方案
Using FakeItEasy I got it to work doing this in the TestInitialize.
this.Controller.ControllerContext = new System.Web.Http.Controllers.HttpControllerContext();
this.Controller.Request = A.Fake<HttpRequestMessage>();
这篇关于单元测试的ASP.NET Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!