0

我正在对一个简单的帖子进行单元测试:

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; 
}
4

3 回答 3

1

使用 FakeItEasy 我让它在 TestInitialize 中工作。

this.Controller.ControllerContext = new System.Web.Http.Controllers.HttpControllerContext();
this.Controller.Request = A.Fake<HttpRequestMessage>();
于 2013-01-16T21:33:18.087 回答
1

Request属性应该是可设置的,因此您只需要设置ControllerContext(它应该有一个无参数的构造函数,因此您甚至不必模拟)。

于 2012-02-28T16:22:47.830 回答
0

您的方法可能会收到 HttpRequestMessage 作为参数。

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

} 

您可以从中获取 RequestUri。在您的单元测试中,您可以放置​​ HttpRequestMessage 对象的测试替身。

于 2012-03-20T16:11:54.543 回答