简体   繁体   中英

Mocking HttpRequestMessage

I have a controller Action as:

[HttpPost]
[EnableQuery]
[ODataRoute("PostData")]
public async Task<string> PostData(HttpRequestMessage message)
{

//Do operations
}

I need to create a mock for this method ,but I am not getting how to pass the parameter "HttpRequestMessage",

because if there was any variable to be passed , then its just initializing with the type like string or int.

How to handle this condition in mock?

HttpRequestMessage is very mutable:

public class HttpRequestMessage : IDisposable
{
    [... ctors]

    public Version Version { get; set; }
    public HttpContent Content { get; set; }
    public HttpMethod Method { get; set; }
    public Uri RequestUri { get; set; }
    public HttpRequestHeaders Headers { get; }
    public IDictionary<string, object> Properties { get; }

    [... Dispose, ToString]
}

So if you just need to set RequestUri for example, you can:

var requestMessage = new HttpRequestMessage() { RequestUri = new Uri("http://www.google.com") };
yourClassInstance.PostData(requestMessage);

Even if you need to add some headers or properties GetRequestContext can create HttpRequestContext from , you can do

requestMessage.Headers.Add("h", "v");
requestMessage.Properties.Add("p", "v");

This design (of HttpRequestMessage ) does not adhere to functional programming principles at all, but at least you can test it easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM