moqing static method call to c# library class

做~自己de王妃 提交于 2019-12-22 11:17:21

问题


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 call 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.


回答1:


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));

        ...
    }


    ..
}



回答2:


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.




回答3:


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...




回答4:


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; 


来源:https://stackoverflow.com/questions/2407038/moqing-static-method-call-to-c-sharp-library-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!