jegan
jegan

Reputation: 300

Why am I getting InvalidComObjectException after creating a WPF window in a NUnit test?

I haven't been able to figure this one out for NUnit yet. There was a similar question asked, here where this exception was being raised. The answer resolves usage with xUnit, and the asker reports that he got it working for MSTest. I have tried calling Dispatcher.CurrentDispatcher.InvokeShutdown(); in the [TearDown], [TestFixtureTearDown], and [Test] methods, and am still getting the exception.

A few more details about my implementation: I've created an InputBox class which extends System.Windows.Window. I made a static method, InputBox.Show(prompt) which executes the following code:

        var input = "";
        var t = new Thread(() =>
            {
                var inputBox = new InputBox(prompt);
                inputBox.ShowDialog();
                input = inputBox.Input;
            }) {IsBackground = true};
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();
        return input;

Any ideas?

Upvotes: 1

Views: 378

Answers (2)

jegan
jegan

Reputation: 300

Thanks for the ideas in the comments about Dispatcher calls. I changed my InputBox.Show method so it now looks like this, and it's working great. I don't have any Dispatcher calls in my unit tests and I'm not getting the exception.

    public static string Show(string prompt)
    {
        string input = null;
        var t = new Thread(() =>
        {
            Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
            {
                var inputBox = new InputBox(prompt);
                inputBox.ShowDialog();
                input = inputBox.Input;
            }));
            Dispatcher.CurrentDispatcher.InvokeShutdown();
        }) { IsBackground = true };
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();
        return input;
    }

Upvotes: 1

Iulian Radulescu
Iulian Radulescu

Reputation: 324

Have you Tried [RequireMTA] (use intelissence to prove the correctness) attribute on top of your test method? ApartmentState.STA - is in my opinion the statement that gives you trouble

Upvotes: 0

Related Questions