2

Consider that I have a MainWindow that has the following button declared in its XAML:

<Button x:Name="MyButton" Command="{Binding SomeCommand}">Click me!</Button>

I want to use UIAutomation inside a Test Project to create a new Window and press this button, however, when doing so I get the following error:

COM object that has been separated from its underlying RCW cannot be used.

For the record, I am not using any COM-objects.

This is how my Test Class is layed out:

[TestClass]
public class UnitTest1
{
    public UnitTest1()
    { }
    private MainWindow _window;
    [TestInitialize]
    public void TestInitialize()
    {
        _window = new MainWindow();
        _window.Show();
    }
    [TestCleanup]
    public void TestCleanup()
    {
        _window.Close();
    }
    [TestMethod]
    public void TestMyButton()
    {
        var myButton = 
            AutomationElement.RootElement.FindFirst(TreeScope.Descendants, 
            new PropertyCondition(AutomationElement.AutomationIdProperty, 
                "MyButton"));

        var pattern = 
            myButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
        pattern.Invoke();
    }
}

Is this not how you are suppose to use UIAutomation inside a unit test?

Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183

1 Answers1

4
    [TestCleanup]
    public void TearDown()
    {
        Dispatcher.CurrentDispatcher.InvokeShutdown();
    }
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
bling
  • 1,121
  • 11
  • 8
  • Thanks, that did the trick. Not using NUnit though so in this case the attribute is `TestCleanupAttribute`. Changed your code to correspond with mstest. By the way, it would be very nice if you updated your answer with an explanation to why this solves the problem. – Filip Ekberg Apr 17 '11 at 07:12
  • See this [link](http://stackoverflow.com/questions/1293402/why-does-wpf-require-a-stathread-attribute-to-be-applied-to-the-main-method) for a more detailed answer. Basically, the test is creating the COM objects without nicely cleaning them up, hence why explicitly calling InvokeShutdown() fixes it. – bling Apr 17 '11 at 14:41