Capture confirm dialog with WatiN

Tonight, I ran into an issue with with WatiN, an automated browser-based test tool for .net.  Let me first describe my setup… I’m using NUnit 2.4 to drive WatiN.  I could have used NUnitAsp, instead of WatiN, but I like the idea of using an actual browser instance rather than mock objects.  Btw, the NUnit support that Resharper provides is just awesome.  I’m sort of pissed that it took me so long to try it out.  Give resharper a try, if you haven’t yet…

So.. back to the problem that I came across tonight.  Everything was peachy until I needed to interact with a javascript confirmation prompt.  This is the solution that works for me:

ConfirmDialogHandler deleteHandler = new ConfirmDialogHandler();

using (new UseDialogOnce(Browser.DialogWatcher, deleteHandler))

{

    Link deleteLink = Browser.Link(Find.ById(“DeleteLink”));

    Assert.IsTrue(deleteLink.Exists);

    deleteLink.ClickNoWait();

 

    deleteHandler.WaitUntilExists();

    deleteHandler.OKButton.Click();

}

Browser.WaitForComplete();

One thing to note is that Browser just represents the IE object that is created in my TextFixtureSetUp method.  The UseDialogOnce class is:

public class UseDialogOnce : IDisposable

{

    private DialogWatcher dialogWatcher;

    private IDialogHandler dialogHandler;

 

    public UseDialogOnce(DialogWatcher dialogWatcher, IDialogHandler dialogHandler)

    {

        if (dialogWatcher == null)

        {

            throw new ArgumentNullException(“dialogWatcher”);

        }

 

        if (dialogHandler == null)

        {

            throw new ArgumentNullException(“dialogHandler”);

        }

 

        this.dialogWatcher = dialogWatcher;

        this.dialogHandler = dialogHandler;

 

        dialogWatcher.Add(dialogHandler);

    }

 

    public void Dispose()

    {

        Dispose(true);

        GC.SuppressFinalize(this);

        return;

    }

 

    protected virtual void Dispose(bool managedAndNative)

    {

        dialogWatcher.Remove(dialogHandler);

 

        dialogWatcher = null;

        dialogHandler = null;

    }

}

It’s important to note that I use the method ClickNoWait() rather than Click(), for the delete link.  This prevents the situation where WatiN is waiting forever for the click event to finish, while IE just sits with the confirm prompt.