Cannot find a Resource with the Name/Key
I'm trying to unit test a user interface using the Silverlight 4 Toolkit.
When I attempt to instantiate the UserControl, it's throwing an exception because in the XAML of the UserControl it's using a Style defined App.xaml.
Is there a way to load the resour开发者_StackOverflow社区ce somehow before I instantiate the UserControl? Am I going about this the wrong way?
Here's the unit test code:
[TestMethod]
public void ExerciseTimePeriodUserInterface()
{
CustomUserControls.TimePeriodFilter timePeriodFilter = new CustomUserControls.TimePeriodFilter();
}
Here's the reference to the style in the UserControl:
<Border Style="{StaticResource FilterBorderWrapper}">
And lastly, here's the style defined in the App.xaml:
<Style TargetType="Border" x:Key="FilterBorderWrapper">
<Setter Property="Background" Value="#F1F5FB" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="#CBD9E9" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="Margin" Value="2" />
</Style>
If all your resources placed into ResorceDictionaries. You can simple create Application instance and add that Dictionary to the resources. Please look at the sample:
Application _app = new Application();
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("pack://application:,,,/Gui.Mvvm;component/Themes/YourResourceDictionary.xaml");
_app.Resources.MergedDictionaries.Add(dictionary);
For my WPF app this works fine. After this code was written I was able to test my Template Selectors, DataTemplate Selectors and so forth. All code using in codebehind calls to
Application.Current.FindResource()
works quite good.
You can't easily unit test User controls out of context. Too many dependencies.
You can test your view models with unit tests (which should be where all your code is anyway) and the Silverlight controls with some form of GUI automation (or humans if you can't afford the latest GUI test tools).
As VC 74 implied, if you are not already using MVVM, you probably should (if you want to do Silverlight unit testing).
Rick,
basically, I was getting the same error. Later then, i simply copied the Resources and all definitions to the Test-Projects App.xaml
file (I also have a Styles.xaml
resource), and my UI Tests work without problems.
Of course, it's never the best solution to copy "anything", but hey, I really don't care about the styles. Plus, you could even define own styles for the UI Testing Panel.
HTH
Thomas
精彩评论