Filip Ekberg
Filip Ekberg

Reputation: 36327

Unit testing with UIAutomation

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?

Upvotes: 2

Views: 1125

Answers (1)

bling
bling

Reputation: 1161

    [TestCleanup]
    public void TearDown()
    {
        Dispatcher.CurrentDispatcher.InvokeShutdown();
    }

Upvotes: 4

Related Questions