MODIFIED: The code uses HttpRequest.InputStream to read request body, parse it and store it. I’d like to be able to unit test this class but I can’t stick anything into the body. Is that possible? Maybe I could hack the A class directly reflection somehow and set _body to some value.
ADDED: here is the simplified design:
class A
{
private string _body;
public string Body { get { return _body; } }
public A(HttpRequest r)
{
{parse r and store data, i.e. query parameter, etc. }
_body = {read body from r.InputStream };
}
}
class B
{
public void ProcessRequest(HttpRequest r)
{
var c = new C(r);
ParseBody(c.Body);
}
}
It’s all good, I indeed can test ParseBody even if it’s private. However I am unit testing class A and that’s where the problem is. I can make Body R/W property but that’s breaking encapsulation, which I hate because A is supposed to be invariant.
The InputStream is a standard Stream, so if you want your unit test parser to parse the contents you just need to pass in an alternate Stream. It doesn’t have to be from an HttpRequest, since that is not what you are testing. You are testing if the parsing works.
If you must couple it with an HttpRequest, then have a look at the HttpRequestBase class which lets you mock the InputStream. But as I mentioned above, that is just an extra method call to get at the stream.