by Njål

WatiN–Pressing enter key in a textbox

WatiN is an awesome test tool for GUI testing using .NET. It allows you to write Integration/GUI tests in .NET – which are executed inside Internet Explorer or Firefox. This enables us to leave all GUI testing to our TeamCity server (as well as deploying code/databases etc.) – which means less errors and shorter development time.

 

A simple WatiN example (MsTest):

[TestMethod]
public void Search_Test()
{
    using (var browser = new IE("http://mysite.com"))
    {
        //ACT & ARRANGE
        const string searchString = "bananas";
        browser.TextField("txtSearchLarge").TypeText(searchString);
        browser.Button("btnSearch").Click();

        //ASSERT
        Assert.AreEqual("http://dev.mysite.com/Search?s=" + searchString, browser.Url, "Url");
    }
}

 

The example above starts up Internet Explorer, types “Bananas” into the search field, and clicks the search button.

It then asserts that the site (javascript) performs as expected – that is – redirecting the user to the search page with the proper querystring.

You can Debug these tests like any other tests, and even watch the test being executed in Internet Explorer.

I recently wanted to test some javascript which was executed upon pressing Enter in a textbox. I couldn’t get it to work , so I went through some posts on Stackoverflow.com – and found a range of different alternatives – which didn’t work properly either.

So I cooked together a combination which seems to work fine. I wrapped it as an extension method:

public static class MyWatiNExtensions
{
    [DllImport("user32.dll")]
    private static extern IntPtr SetFocus(IntPtr hWnd);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    public static void TypeTextQuickly(this TextField textField, string text)
    {
        textField.SetAttributeValue("value", text);
    }

    public static void PressEnter(this TextField textField)
    {
        SetForegroundWindow(textField.DomContainer.hWnd);
        SetFocus(textField.DomContainer.hWnd);
        textField.Focus();
        System.Windows.Forms.SendKeys.SendWait("{ENTER}");
        Thread.Sleep(1000);
    }
}

This makes it very easy to press the Enter key in a test.

browser.TextField("txtSearchLarge").PressEnter();

 

Happy testing!