moqing static method call to c# library class

半城伤御伤魂 提交于 2019-12-06 03:01:57

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

        ...
    }


    ..
}

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

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