简体   繁体   中英

How to unit test a class derived from NetworkStream?

As part of a project I have a class which derives from NetworkStream. In this case it provides wrapped implementations of methods such as Read and ReadByte to provide some context specific safety (it calls the base methods with some additional logic).

But testing this is an issue. The class requires a Socket in the constructor (concrete type) and mocking that does not work for me (using Moq here, perhaps something like TypeMock would, but I would like to avoid costly tooling).

Another alternative might be to compose rather than inherit, and create a class which wraps a NetworkStream and implements my own interface similar to NetworkStream. But this is also a problem. Most consumers of streams in the BCL such as StreamReader etc. require a concrete Stream or derived type, and therefore would not work with my composed class.

So, can anyone think of any alternatives? It's not something I'd feel happy about leaving without decent coverage - it's an area where much could go wrong, and it should be solid.

You might want to take a look at the pex and moles project http://research.microsoft.com/en-us/projects/pex/ . More specifically the Moles part. Here's a direct link to a getting started. http://research.microsoft.com/en-us/projects/pex/molestutorial.pdf

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