Reading from closed stream
I want to test my request builder in unit tests. But I have problem when I want to test my method that makes POST request.I want to test it's content in request stream. But the problem is that that I cannot read this stream in my test so I cannot test whether my data is written in right way inside request. I have this problem because when I close stream after wr开发者_JS百科iting in it in my Request builder class. I cannot open it for reading because after calling the Close() method on stream it becomes unreadable. So, is there a way to read a stream after calling Close() method?
If this isn't possible, how would you solve this problem?
Try to create some wrapper around your Stream and extract it's interface. This interface may contain only members necessary in your other code. Use that interface in your code and allow to inject/create instance of different specific types to be used - e.g. create mandatory constructor's parameter that sets a field in a class containing your code. Then create some mock realizing that interface and use it in your unit tests.
Once the stream is closed, its contents are effectively inaccessible, since the underlying buffer is either released or passed to another entity for processing or disposal.
I'm not sure which Stream class you're using, but most provide a .Seek method and a .Position property to rewind the stream. Try that instead of closing the stream. (Though you will still need to close the stream once you're really done with it.)
精彩评论