任何人都可以解释为什么,当我通过调试器进行单元测试时,我在查看对象或属性时获得空引用。例如: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
我知道我做错了什么,但任何人都可以解释什么?
谢谢, 马克
所以我尝试使用Justin Angels的WaitFor()方法,使用EnqueueConditional等待Loaded事件触发。我仍然没有看到具体的物体,所以为了简单起见我删除了这些物体。 – 2009-04-08 15:25:05
加载可能不会在单元测试下触发。正如Kent提到的那样,Loaded只有在元素被添加到可视化树中时才会发生。除非你的单元测试实际显示shell,否则Loaded不会触发。 – 2009-04-09 14:59:07