2009-04-08 70 views
1

任何人都可以解释为什么,当我通过调试器进行单元测试时,我在查看对象或属性时获得空引用。例如:Silverlight MVVM单元测试解释

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   } 

[9号线当我在我的ViewModel字段设置为壳视图的DataContext的我得到一个“对象未设置为实例...”异常。我确信我的datacontext正在设置在我的shell.xaml.cs中;整个文件:

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 

我知道我做错了什么,但任何人都可以解释什么?

谢谢, 马克

回答

2

我猜测问题是你正在隔离实例化Shell对象。您是否确认Shell_Loaded(Loaded事件)甚至被调用?

为什么你不在xaml中创建视图模型作为静态资源?有了MVVM,我通常将它创建为xaml中的静态资源,然后将其作为LayoutRoot中的数据上下文...将其绑定为xaml中的所有内容。

2

你设置DataContext期间Loaded事件,当你的控制实际上是加载到可视化树被提出。因此,您的DataContext将不会被设置,因为您所做的全部都是构建视图。您可以通过使用附加的调试器运行单元测试并在Loaded处理程序中设置断点来轻松进行验证。

+0

所以我尝试使用Justin Angels的WaitFor()方法,使用EnqueueConditional等待Loaded事件触发。我仍然没有看到具体的物体,所以为了简单起见我删除了这些物体。 – 2009-04-08 15:25:05

+0

加载可能不会在单元测试下触发。正如Kent提到的那样,Loaded只有在元素被添加到可视化树中时才会发生。除非你的单元测试实际显示shell,否则Loaded不会触发。 – 2009-04-09 14:59:07