Reputation: 728
I need to open my Window.xaml
in Unit Test. I tried a simple code as follows:
[Test]
public void Test_window()
{
var mw = new MainWindow();
mw.Show();
}
The above code ends with an error.
The calling thread must be STA, because many UI components require this.
Afterwards, I tried the below code :
[Test]
public void Test_window()
{
Thread th = new Thread(new ThreadStart(delegate
{
var mw = new MainWindow();
mw.Show();
}));
th.ApartmentState = ApartmentState.STA;
th.Start();
}
In this case , the test passes successfully, but no window is shown. Since I am new to WPF, it would be appreciable if any suggestions or guidance are available here.
Thanks.
Upvotes: 3
Views: 4258
Reputation: 8500
I think it is shown, but very fast, because you don't wait for the window. You could do something like this:
[Test]
public void Test_window()
{
var showMonitor = new ManualResetEventSlim(false);
var closeMonitor = new ManualResetEventSlim(false);
Thread th = new Thread(new ThreadStart(delegate
{
var mw = new MainWindow();
mw.Show();
showMonitor.Set();
closeMonitor.WaitOne();
}));
th.ApartmentState = ApartmentState.STA;
th.Start();
showMonitor.WaitOne();
Task.Delay(1000).Wait();
//anything you need to test
closeMonitor.Set();
}
It is possible to achieve the same with only one monitor, but it's more readable in this way.
Upvotes: 3