从封闭流中读取
我想在单元测试中测试我的请求构建器。但是当我想测试发出 POST 请求的方法时遇到问题。我想测试请求流中的内容。 但问题是我无法在测试中读取此流,因此我无法测试我的数据是否以正确的方式写入请求内。 我遇到这个问题是因为当我在请求构建器类中写入流后关闭流时。我无法打开它进行阅读,因为在流上调用 Close() 方法后,它变得不可读。 那么,有没有办法在调用 Close() 方法后读取流呢?
如果这不可能,您将如何解决这个问题?
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 writing 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试围绕您的 Stream 创建一些包装器并提取它的接口。该接口可能只包含其他代码中必需的成员。
在代码中使用该接口,并允许注入/创建要使用的不同特定类型的实例 - 例如,创建强制构造函数的参数,该参数在包含代码的类中设置字段。
然后创建一些实现该接口的模拟并在单元测试中使用它。
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.
一旦流关闭,其内容实际上就不可访问,因为底层缓冲区要么被释放,要么被传递到另一个实体进行处理或处置。
我不确定您使用的是哪个 Stream 类,但大多数都提供 .Seek 方法和 .Position 属性来倒带流。尝试这样做而不是关闭流。 (尽管当你真正完成后,你仍然需要关闭流。)
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.)