Create method that returns IDisposable in custom mock class
I am trying to educate some people in the use of real unit tests since most of their automated tests are integration ones.
In order to do so I want to refactor a class so that I can test it in isolation without its dependencies.
For that I have the following restrictions: 1. I cannot use any mocking framework so I have to create custom mocks for this. 2. I cannot modify the class that will be mocked to change any private methods to protected or public, or change the methods to be virtual so I cannot inherit from this class and override the methods.
So in the method that I want to test I have the following using statement:
using(myObje开发者_开发知识库ct.CreateScope())
{
.... do something
}
So far what I plan on doing is:
1. Extract an interface from the myObject's class. 2. Inject the interface on the SUT using a property.Of course the "CreateScope" method will be part of the interface which is defined like this:
public IDisposable CreateScope();
So on my custom mock I would like to do something like:
public IDisposable CreateScope()
{
return new AnyDisposableObject();
}
My question would be:
Considering that the message that testing classes in isolation provides lots of benefits that integrated tests cannot, what would be the least painful and clearest way to implement the "CreateScope" method in the custom mock?
Should I create an empty fake object whose only purpose is to implement IDisposable?
Should I use any object from the .Net framework that implements IDisposable? Is there a better way than the two options above?Thanks in advance.
UPDATE: For the sake of clarity
using(myObject.CreateScope())
{
var local = parameter.Where(o => !myObject.Contains(o)).Select(o).ToList();
...
myObject.Register(newInstance);
...
return myObject.GetList();
}
I will be testing the logic within the "using" statement. The myObject object will be mocked just to provide values when calling methods that return them or empty methods for void ones. What the CreateScope method does is to put a lock in a protected Dictionary, but I'm not interested to test that functionality with this.
Hope this clarifies the intent.
Try the following Mock object, that implements IDisposable:
class MockDisposable : IDisposable
{
bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed) // only dispose once!
{
if (disposing)
{
// Not in destructor, OK to reference other objects
}
// perform cleanup for this object
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
// tell the GC not to finalize
GC.SuppressFinalize(this);
}
~MockDisposable()
{
Dispose(false);
}
}
精彩评论