CK__
CK__

Reputation: 1311

how to resolve error while writing nunit test case for Application.Current.FindResource() in WPF

I am writing test case for a class, having Application.Current.FindResource()method. But while passing through above code in i am getting error like "ObjectNotInitialized". Following is the code:-`public void ContactListViewModel()

{
    var app = Application.Current;
    var default_Flag = (DrawingImage) app.FindResource("Unknown_Flag");
}

and following is the error, i am getting:

{"Object reference not set to an instance of an object."}

please, tell me how to write test case for this method

Upvotes: 0

Views: 530

Answers (1)

Ouarzy
Ouarzy

Reputation: 3043

I would nuance the comment of Sheridan as an answer: In WPF you test your UI by testing your ViewModel (this is one of the reason why MVVM is so important for a WPF project). If you want more than that, yes you can use the UI automation.

As often here, you can't test your class because it is coupled to the Application. (ie: you are stuck because of your call to Application.Current)

Now imagine if instead of this direct call, you inject (via a parameter) the current application as an interface. Then this interface could be mock, thus your class will become testable (your dependency will be inverted).

In conclusion you actually have a way to test that even without refactoring, using MS fakes. But I give it to you just as an information, I highly discourage you to use it, especially if you are a beginner for unit testing. It is more usefull when you want to test legacy code.

Upvotes: 1

Related Questions