1

I'm using TDD and creating unit tests for System.IO.Stream objects that use unmanaged resources. My project consists of many such streams and I want to test if the implementations actually clean up their unmanaged resources when they are disposed.

Any idea how I can do this?

I might just be a bit tired this morning, but all I can come up with is creating and disposing 1k instances and look at memory consumption.

I also have to think of "what if they don't timeout from Read()", so if there is some great universal super-fantastic way of testing streams that could be relevant.

Tedd Hansen
  • 12,074
  • 14
  • 61
  • 97

1 Answers1

0

Depends on what the resource is but if you was saving a stream to disk, and you code fellover without cleaning up, attempting to delete the file would cause a problem.

However a TTD approach would be to cause an exception, which your code should handle and throw (preferred but not always). Then have the test, pick it up as an expected exception and then check the resources to see if they've been correctly tidied up. That of course is testing for known situations, no matter what is a bit more difficult.

We too use a lot of streams, but basically we followed FxCop and best practice, wrote some utility routines and helper classes. After that it was religiously using using, or implementing IDisposable.

One other thing I'd thoroughly recomend is using the "full" version of FileStream for read and write to disk.

You don't see something like

XmlDocument doc = new XmlDocument()
doc.Load("myxml.xml");

Instead we do

XmlDocument doc = new XmlDocument()
using(FileStream fs = new FileStream("myxml.xml",FileMode.Open, FileAccess.Read))
{
  doc.load(fs);
}

Nail down as many unknowns as you can, if your chosen deity smiles upon you, it might all of them in a pragmatic and pratical sense.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39