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):

public void Search_Test()
    using (var browser = new IE(""))
        //ACT & ARRANGE
        const string searchString = "bananas";

        Assert.AreEqual("" + 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 – 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
    private static extern IntPtr SetFocus(IntPtr hWnd);

    [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)

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



Happy testing!