This seems like an easy enough issue but I can't seem to find the keywords to effect my searches.
I'm trying to unit test by mocking out all objects within this method call. I am able to do so to all of my own creations except for this one:
public void MyFunc(MyVarClass myVar)
{
Image picture;
...
picture = Image.FromStream(new MemoryStream(myVar.ImageStream));
...
}
FromStream is a static c开发者_开发技巧all from the Image class (part of c#). So how can I refactor my code to mock this out because I really don't want to provide a image stream to the unit test.
You can create an IImageLoader interface. The "normal" implementation just calls Image.FromStream, while your unit test version can do whatever you need it to do.
Moq and most other mocking frameworks don't support mocking out static methods. However, TypeMock does support mocking out static methods and that might be of interest to you if you're willing to purchase it. Otherwise, you'll have to refactor so that an interface can be mocked...
You could wrap the static function into Func type property which can be set by the unit test with a mock or stub.
public class MyClass
{
..
public Func<Image, MemoryStream> ImageFromStream =
(stream) => Image.FromStream(stream);
public void MyFunc(MyVarClass myVar)
{
...
picture = ImageFromStream(new MemoryStream(myVar.ImageStream));
...
}
..
}
This can be acheived with Moles, a Visual Studio 2010 Power Tools. The Moles code would look like this:
// replace Image.FromStream(MemoryStream) with a delegate
MImage.FromStreamMemoryStream = stream => null;
精彩评论