我單元測試一個簡單的帖子:單元測試的ASP.NET Web API
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;
}
然而,「URL」和「請求」顯然將是零。
有嘲笑ControllerContext和HttpContext的替代方案嗎?
更新:
將其改爲:
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;
}
更新2:
這是更好的:
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;
}
相關:http://stackoverflow.com/questions/10042290/sample-code-for-unit-testing-api-controllers/22200520#22200520 – 2014-03-06 10:06:59