If you already have your code and are asking how to test it, then you're not writing your tests first...so aren't really doing TDD.
However, what you have here is a dependency. So the TDD approach would be to use Dependency Injection. This can be made easier using an IoC container like Unity.
When doing TDD "properly", your thought processes should run as follows in this sort of scenario:
- I need to do a
Foo
- For this I will rely on an external dependency that will implement an interface (new or pre-existing) of
IMyDisposableClass
- Therefore I will inject an
IMyDisposableClass
into the class in which Foo
is declared via its constructor
Then you would write one (or more) tests that fail, and only then would you be at the point where you were writing the Foo
function body, and determine whether you needed to use a using
block.
In reality you might well know that yes, you will use a using
block. But part of the point of TDD is that you don't need to worry about that until you've proven (via tests) that you do need to use an object that requires this.
Once you've determined that you need to use a using
block you would then want to write a test that fails - for example using something like Rhino Mocks to set an expectation that Dispose
will get called on a mock object that implements IMyDisposableClass
.
For example (using Rhino Mocks to mock IMyDisposableClass
).
[TestFixture]
public class When_calling_Foo
{
[Test]
public void Should_call_Dispose()
{
IMyDisposableClass disposable = MockRepository.GenerateMock<IMyDisposableClass>();
Stuff stuff = new Stuff(disposable);
stuff.Foo();
disposable.AssertWasCalled(x => x.Dispose());
}
}
Class in which your Foo function exists, with IMyDisposableClass
injected as a dependency:
public class Stuff
{
private readonly IMyDisposableClass _client;
public Stuff(IMyDisposableClass client)
{
_client = client;
}
public bool Foo()
{
using (_client)
{
return _client.SomeOtherMethod();
}
}
}
And the interface IMyDisposableClass
public interface IMyDisposableClass : IDisposable
{
bool SomeOtherMethod();
}