Unit Testing ASP.NET Web API

瘦欲@ 提交于 2020-01-03 05:08:08

问题


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

回答1:


The Request property should be settable, so you only have to set the ControllerContext (which should have a no-arg constructor so you shouldn't even have to mock).




回答2:


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>();



回答3:


Your method might recieve HttpRequestMessage as parameter.

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

} 

You can take RequestUri from it. In your unit tests you can put test double of HttpRequestMessage object.



来源:https://stackoverflow.com/questions/9483663/unit-testing-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!