Build/Test Issues

System.InvalidOperationException. The thread must be STA

Started by CodeAdze on 7,319 views

Hi,
I have the following test fixture.

Imports System.Windows.Controls
Imports NUnit.Framework


<TestFixture>
Public Class SearchResultPaserTests
  <Test>
  <STAThread>
  Public Sub ParseMethodReturnsComboBoxItem()
    Dim srp As New SearchResultPaser

    Assert.AreEqual(GetType(ComboBoxItem), srp.Parse(New SearchResult()).GetType())
  End Sub
End Class


Which tests the following class which is in a class library referenced by a WPF application.


Imports System.Windows.Controls

Public Class SearchResultPaser
  <STAThread>
  Public Function Parse(result As SearchResult) As ComboBoxItem

   [h] Return New ComboBoxItem()[/h]
  End Function
End Class


I am getting a "Invalid Operation Exception : The calling thread must be STA, because many UI components require this." when I try to return a new ComboBoxItem . After reading this post I tried adding the <STAThread> attributes but still no joy.
The SearchResultPaser class works fine when called form my WPF app presumably because it is then running on WPF's UI thread.

What can I do to resolve this.

Thanks
Hi,

seems you are using NUnit 3 where STAThread is no longer supported.

Please use the Apartment state instead:

<TestFixture>
Public Class SearchResultPaserTests
<Test>
<Apartment(ApartmentState.STA)>
Public Sub ParseMethodReturnsComboBoxItem()
Dim srp As New SearchResultPaser

Assert.AreEqual(GetType(ComboBoxItem), srp.Parse(New SearchResult()).GetType())
End Sub
End Class


Regards
Hi Ralf,
Thanks for your help with this, yes I was using NUnit 3 which I forgot to mention in my post and your suggestion to change <STAThread> to <Apartment(ApartmentState.STA)> worked perfectly.

Thanks again!

Post a reply

Log in to reply.