【问题标题】:How to mock Application.Current for unit-testing?如何模拟 Application.Current 进行单元测试?
【发布时间】:2013-08-01 08:48:08
【问题描述】:

我有这个:

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

还有这个:

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

当我对它进行单元测试 (MSTest) 时,它显然会引发 IOException(因为 Application.Current 为空,所以 pack://application:,,,/... 指向无处)并出现此错误:

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.

我如何模拟/注入解决它所需的任何东西?

【问题讨论】:

  • 我认为将 Uri 注入到 GrayscaleEffect 中会更容易。这对你有用吗?
  • @DanielSklenitzka:是的。怎么样?

标签: c# wpf unit-testing mocking mstest


【解决方案1】:

好的,知道了,感谢Will

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

var window = new MainWindow();

【讨论】:

    【解决方案2】:

    Tal 的回答对我不起作用,我只是在运行我的测试和 Application.Current 之前在下面调用:

    var app = new Application();
    

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多