2012-02-28 112 views
0

我單元測試一個簡單的帖子:單元測試的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; 
} 
+0

相關:http://stackoverflow.com/questions/10042290/sample-code-for-unit-testing-api-controllers/22200520#22200520 – 2014-03-06 10:06:59

回答

1

Request屬性應該是可設置的,所以你只需要設置ControllerContext(它應該有一個無參數con結構,所以你甚至不應該模擬)。

0

您的方法可能會收到HttpRequestMessage作爲參數。

public HttpResponseMessage<Document> PostDocument(Document document, HttpRequestMessage message) 
{ 

} 

您可以從中獲取RequestUri。在你的單元測試中,你可以把HttpRequestMessage對象的測試加倍。

1

使用FakeItEasy我在TestInitialize中完成了這個工作。

this.Controller.ControllerContext = new System.Web.Http.Controllers.HttpControllerContext(); 
this.Controller.Request = A.Fake<HttpRequestMessage>(); 
0

您可以使用MyTested.WebApi,它爲您嘲笑一切。示例測試:

MyWebApi 
    .Controller<WebApiController>() 
    .Calling(c => c.SomeAction()) 
    .ShouldReturn() 
    .Ok() 
    .WithResponseModelOfType<ResponseModel>() 
    .Passing(m => 
    { 
     Assert.AreEqual(1, m.Id); 
     Assert.AreEqual("Some property value", m.SomeProperty); 
    });