I'm in the process of migrating a large .Net 4.x solution to .Net6, and now that I have the first few projects building successfully I thought I'd have a go at running the unit tests (MSTest project). However many tests are failing with the above message, specifically those that test code in a WPF project.
All tests pass in the 4.x solution. Why would they be failing in the .Net5 MSTest project, and is there a way to get them working?
Edit: I know unit tests shouldn't be testing UI functionality, but I want to point out that I'm unit testing MVVM view models. Having said this, there will always be something that needs the STA thread, whether it's setting the mouse cursor during a long running operation, or updating an observable collection from an event handler, requiring the use of the Dispatcher. I have written wrappers for this sort of thing, checking if I'm running in a unit test or whether the dispatcher is available. The failing code is typically where I've forgotten to use such wrapper classes, which (for whatever reason) worked fine in VS2019 and .Net Framework 4.x.
CodePudding user response:
I don't know how true this is but I read on a blog somewhere (which I can't find now) that MSTest in .Net Framework ran tests as STA, whereas in .Net Core/5/6 the tests now run as MTA. I didn't want to switch thousands of unit tests to NUnit, so my solution was to create my own custom [STATestClass] and [STATestMethod] attributes as detailed here: https://www.meziantou.net/mstest-v2-customize-test-execution.htm