如何在HttpRequestMessage上模拟CreateResponse <T>扩展方法


69

我正在使用ASP.Net MVC 4 RC的ApiController,并且正在尝试对GET方法进行单元测试。

此方法使用上的CreateResponse<T>方法HttpRequestMessage,但我不知道如何模拟此方法或使其正常运行。

该方法的主体包含以下内容:

MediaTypeHeaderValue header = new MediaTypeHeaderValue(versionedSmartBlock.ContentType);
var response = Request.CreateResponse<SmartBlock>(
    HttpStatusCode.OK, versionedSmartBlock, header);

在单元测试中,我创建一个空的HttpRequestMessage

CallsController api = new CallsController(
    managerMock.Object, config, adapterFactoryMock.Object);
api.Request = new HttpRequestMessage(
    HttpMethod.Get, "http://localhost/Initiate?ern=%2B44123456789");    
var response = api.Get("+44123456789", null);

但这只会生成一个InvalidOperationException

该请求没有关联的配置对象,或者提供的配置为空。

有没有人知道如何配置,HttpRequestMessage以便该CreateResponse方法真正发挥作用?


1
这看起来像它解决了同样的问题:stackoverflow.com/questions/10868673/...
伊恩·吉尔罗伊

Answers:



0

带有VB的WebAPI 1!

我设法将您上面链接中的响应混合在一起,以使其像下面这样简单地工作:

Dim request As HttpRequestMessage = New HttpRequestMessage()
Return request.CreateResponse(HttpStatusCode.BadRequest, myCustomClassObject, GlobalConfiguration.Configuration)

只是发布以防万一。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.