Since you want to mock the resource class I assume you already have
interface IResource : IDisposable
{
void DoSomething();
}
class DisposableResource : IResource
{
public void Dispose() { Console.WriteLine("That's it. I'm outta here!"); }
public void DoSomething() { Console.WriteLine("Hard work this"); }
}
To be able to inject the obj, you need a seam.. i.e. GetResource()
class MyClass
{
protected virtual IResource GetResource()
{
return new DisposableResource();
}
public void MyMethod1()
{
using (IResource r = GetResource())
{
r.DoSomething();
}
}
}
In your test code, simply subclass and override GetResource() to return a mock.
class MySubClassForTest : MyClass
{
protected override IResource GetResource()
{
return new MockResource();
}
}
class MockResource : IResource // or use a mock framework to create one
{
public void DoSomething() { Console.WriteLine("Me work?"); }
public void Dispose() { Console.WriteLine("Disposed Mock!"); }
}
That's it.
MyClass obj = new MyClass(); // production code
obj.MyMethod1();
obj = new MySubClassForTest(); // test code
obj.MyMethod1();