我有以下控制器動作測試的WebAPI控制器Url.Link
public void Post(Dto model)
{
using (var message = new MailMessage())
{
var link = Url.Link("ConfirmAccount", new { model.Id });
message.To.Add(model.ToAddress);
message.IsBodyHtml = true;
message.Body = string.Format(@"<p>Click <a href=""{0}"">here</a> to complete your registration.<p><p>You may also copy and paste this link into your browser.</p><p>{0}</p>", link);
MailClient.Send(message);
}
}
爲了驗證這一點,我需要設置控制器上下文
var httpConfiguration = new HttpConfiguration(new HttpRouteCollection { { "ConfirmAccount", new HttpRoute() } });
var httpRouteData = new HttpRouteData(httpConfiguration.Routes.First());
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost");
sut = new TheController
{
ControllerContext = new HttpControllerContext(httpConfiguration, httpRouteData, httpRequestMessage),
MailClient = new SmtpClient { PickupDirectoryLocation = location }
};
這似乎是一個很大的設置來測試創建的鏈接。有沒有更乾淨的方法來做到這一點?我已經閱讀了關於內存中的服務器,但看起來它比httpclient更適用於直接測試控制器。
+1我認爲REST服務的重點在於允許可鏈接的資源。我對WebAPI Link/Url實用程序非常不滿。引用路由名稱似乎很脆弱,測試故事同樣痛苦。希望有一些改進... – 2013-04-10 16:40:09