Moqing静态方法对C#库类的调用 [英] moqing static method call to c# library class
问题描述
这似乎是一个简单的问题,但我似乎找不到能影响搜索的关键字.
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是Image类(属于c#的一部分)的静态调用.因此,由于我真的不想为单元测试提供图像流,因此如何重构我的代码以进行模拟.
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.
推荐答案
您可以将静态函数包装到Func类型属性中,该属性可以由单元测试使用模拟或存根设置.
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));
...
}
..
}
这篇关于Moqing静态方法对C#库类的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!