Question

I have a wpf application with a simple window that shows a text in a textbox bound to a property of the ViewModel. When I execute the application I can see the text in the textbox, but when I execute a white based test, I have different results, at random:

  • most of the times, it's not bound and the test fails.
  • sometimes it's bound (I can see the text in the window raised by white), but white throws an exception when the code wants to get the window.
  • sometimes (really few) it works.

The code I'm trying to execute is this:

<Window x:Class="Sample.Tests.Wpf.MainWindow"     
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">   
  <Grid>
    <TextBox Height="23"
             HorizontalAlignment="Left"
             Margin="22,19,0,0"
             Name="name"
             Text="{Binding Path=CountryName}" 
             VerticalAlignment="Top"
             Width="120" />
  </Grid>
</Window>

The code behind:

namespace Sample.Tests.Wpf
{
  public partial class MainWindow
  {
    public MainWindow()
    {
      InitializeComponent();
      Loaded += delegate { DataContext = new MainWindowViewModel
                                         {
                                           CountryName = "Argentina"
                                         };
                          };
    }
  }
}

and the test looks like:

var app = Application.Launch("Sample.Tests.Wpf.exe");
var window = app.GetWindow("MainWindow");
Assert.IsNotNull(window);
var textbox = window.Get<TextBox>("name");
Assert.AreEqual("Argentina", textbox.Text);

Any idea?

Was it helpful?

Solution

The Loaded event is not fired until the window is about to be rendered. My guess is that it has something to do with the timing of that event.

Does it work if you just assign the DataContext instead of waiting to respond?

namespace Sample.Tests.Wpf
{
    public partial class MainWindow
    {
         public MainWindow()
         {
              InitializeComponent();
              DataContext = new MainWindowViewModel
                                     {
                                       CountryName = "Argentina"
                                     };
         }
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top