How to mock Application.Current for unit-testing?

泄露秘密 提交于 2019-12-13 15:04:59

问题


I have this:

<Image.Effect>
    <fx:GrayscaleEffect DesaturationFactor="0"/>
</Image.Effect>

and this:

public class GrayscaleEffect : ShaderEffect{
    private static PixelShader _pixelShader = new PixelShader()
        {
            UriSource = new Uri(@"pack://application:,,,/Effects/GrayscaleEffect.ps")
        };
    /* ... rest of the class ... */
}

When I unit-test it (MSTest), it obviously raises IOException (since Application.Current is null, so pack://application:,,,/... points to nowhere) with this error:

Assembly.GetEntryAssembly() returns null. Set the Application.ResourceAssembly property or use the pack://application:,,,/assemblyname;component/ syntax to specify the assembly to load the resource from.

How do I mock/inject whatever needed to resolve it ?


回答1:


Ok, got it, thanks to Will:

if(Application.ResourceAssembly == null)
    Application.ResourceAssembly = typeof(MainWindow).Assembly;

var window = new MainWindow();



回答2:


Tal's answer didnt work for me, I am just calling below before running my test and Application.Current is populated:

var app = new Application();


来源:https://stackoverflow.com/questions/17989241/how-to-mock-application-current-for-unit-testing

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