I am writing a unit test for a WebApi controller that reads a POST body from Request.InputStream. I need to set the inputstream property of HttpContext.Current.Request.InputStream, or set the inputstream’s contents. Here is my unit test code so far, but it keeps throwing exceptions:
var originalStream = HttpContext.Current.Request.InputStream;
Stream newStream = new MemoryStream(ASCIIEncoding.Default.GetBytes("Test String"));
var propInfo = originalStream.GetType().GetProperty("CanWrite");
propInfo.SetValue(originalStream, true);
newStream.CopyTo(originalStream);
propInfo.SetValue(originalStream, false);
I get the following exception on the SetValue line:
ArgumentException: Property set method not found
Am I going about this all wrong? My controller reads the input stream and deserializes it into JSON, so I need to be able to insert data into that stream. I just don’t know how to do it. Many thanks.
public abstract bool CanWrite { get; }. There is not setter on that property.. hence your error.In your example,
originalStreamwill be of typeStream. Wrap it in another stream for your test. You aren’t testing theHttpRequest.InputStream, you’re testing the deserialization ….. etc.
You may even consider skipping using the request input altogether since you aren’t really testing that.
EDIT:
To expand a bit more. You should move this out of the controller action.. do something like the below:
Then you can test the stream reading and the deserialization in isolation.
Does that make sense or have I made it more complex? :/