Como invocar o Dispatcher WPF na Nunit?
-
20-09-2019 - |
Pergunta
Quero testar um aplicativo que renderize um bloco de texto com um valor de campo de dados. Eu gostaria de obter a largura real e a altura real, uma vez que a renderização seja concluída. Tudo funciona bem. O problema veio primeiro, quando tentei testar o aplicativo. Não consigo invocar o despachante do projeto de teste.
A seguir, o código.
this.Loaded += (s, e) =>
{
TextBlock textBlock1 = new TextBlock();
//// Text block value is assigned from data base field.
textBlock1.Text = strValueFromDataBaseField;
//// Setting the wrap behavior.
textBlock1.TextWrapping = TextWrapping.WrapWithOverflow;
//// Adding the text block to the layout canvas.
this.layoutCanvas.Children.Add(textBlock1);
this.Dispatcher.BeginInvoke(DispatcherPriority.Background,
(Action)(() =>
{
//// After rendering the text block with the data base field value. Measuring the actual width and height.
this.TextBlockActualWidth = textBlock1.ActualWidth;
this.TextBlockActualHeight = textBlock1.ActualHeight;
//// Other calculations based on the actual widht and actual height.
}
));
};
Acabei de começar a usar a Freira. Então, por favor me ajude.
Obrigado
Solução
Eu não usei o Nunit para escrever testes de unidade antes, mas esse é um problema comum para os testes de unidade VS. O que pode acabar acontecendo é que cada teste usa um despachante diferente e o WPF exige que você use o mesmo despachante. Para contornar isso, crie uma classe estática para armazenar em cache o despachante e invocar tudo através dela.
Outras dicas
Você pode querer olhar para http://www.codeproject.com/kb/wpf/unittestdispatchertimer.aspxLida com um DispatcherTimer
em wpf e freira que, por sua vez, usa o Dispatcher
.
Editar
A partir do link, tente fazer isso antes do teste:
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, testMethod);
// Start the worker thread's message pump
Dispatcher.Run(); // This will block until the dispatcher is shutdown
E pare depois do teste.
Dispatcher disp = Dispatcher.CurrentDispatcher;
// Kill the worker thread's Dispatcher so that the
// message pump is shut down and the thread can die.
disp.BeginInvokeShutdown(DispatcherPriority.Normal);