views:

794

answers:

2

Can anyone explain why, when I step through my unit tests with the debugger, that I get null references whenlooking at objects or properties. For example:

1      [TestMethod]
2            [Description("Test to confirm that upon initial class creation, the login view is loaded as the default content for the TaskRegion.")]
3            public void Shell_Initialisation_LoginViewIsLoadedByDefault()
4            {
5                Shell shell = new Shell();
6    
7                TestPanel.Children.Add(shell);
8    
9                Shell_ViewModel viewModel = shell.DataContext as Shell_ViewModel;
10   
11               Assert.IsTrue(viewModel.TaskRegionContent is ContentControl);
12   
13               EnqueueTestComplete();
14           }

[Line 9] When I set my viewModel field to the DataContext of the shell view I get a "object not set to instance..." exception. I know for sure that my datacontext is being set in my shell.xaml.cs; entire file:

1    using System.Windows;
2    
3    namespace eg.WorkManager.UI.Shell
4    {
5        public partial class Shell
6        {
7    
8            public Shell()
9            {
10               InitializeComponent();
11               this.Loaded += new RoutedEventHandler(Shell_Loaded);
12           }
13   
14           void Shell_Loaded(object sender, RoutedEventArgs e)
15           {
16               this.DataContext = new Shell_ViewModel();
17           }
18       }
19   }
20

I know I'm doing something wrong, but can anyone explain what?

Thanks, Mark

+2  A: 

You're setting the DataContext during the Loaded event, which is raised when your control is actually loaded into the visual tree. Therefore, your DataContext won't be set because all you've done is constructed the view. You can easily verify by running your unit tests with a debugger attached and setting a breakpoint in the Loaded handler.

HTH, Kent

Kent Boogaart
So I tried using Justin Angels idea of a WaitFor() method, that uses an EnqueueConditional to wait for the Loaded event to fire. I still don't see the concrete objects so I removed that for simplicity.
Mark Cooper
Loaded will likely not fire under a unit test. As Kent mentioned, Loaded only happens when an element is added to the visual tree. Unless your unit test actually displays the shell, Loaded will not fire.
Jared Bienz - MSFT
+2  A: 

I am guessing that the problem is that you are instantiating the Shell object in isolation. Have you confirmed that Shell_Loaded (the Loaded event) is even being called?

Why are you not creating your view model as a static resource in your xaml? With MVVM, I usually create it as a static resource in the xaml and then bind it as the data context in the LayoutRoot... all in xaml.

Brian Genisio
I'm a developer, old habits die hard ;-) I'll try that and see if I get better results. thanks
Mark Cooper