Tar
Tar

Reputation: 9035

How to mock Application.Current for unit-testing?

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 ?

Upvotes: 3

Views: 6608

Answers (2)

Bek Raupov
Bek Raupov

Reputation: 3777

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

Upvotes: 4

Tar
Tar

Reputation: 9035

Ok, got it, thanks to Will:

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

var window = new MainWindow();

Upvotes: 3

Related Questions