Wednesday, March 26, 2008

C# test automation with Internet Explorer

As a follow up on my previous post, I had the idea you can do the same in managed code (in your test library, for instance). Although this won't exactly be a unit test (especialy with the example search form, it's more integration testing), it can be usefull in some scenarios.

You need a reference to two COM dll's,
Microsoft HTML Object Library
Microsoft Internet Controls

After that, you can use the following example code inside your test (I present it here as one block. Some things can be put in test setup and teardown):

SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorerClass();
object missing = new object();
ie.Navigate("http://localhost/Default.aspx", ref missing, ref missing, ref missing, ref missing);
ie.Visible = true;
while (ie.Busy)
mshtml.HTMLDocumentClass doc = ie.Document as mshtml.HTMLDocumentClass;
doc.getElementById("searchbox").setAttribute("value", "test", 0);
while (ie.Busy)
string bodytext = doc.body.innerHTML;
Debug.Assert( bodytext.IndexOf("documents found")>0);



Smridh said...


You may want to attach an EventHandler to make the current thread wait until the document is completely loaded.


AutoResetEvent documentComplete;

// Opening an Internet Explorer Window
InternetExplorer ie = new InternetExplorerClass();
// Set OnIEDocumentComplete function to be triggered when document is loaded
ie.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(OnIEDocumentComplete);
ie.Visible = true;

// Setting the documentComplete Event to false
documentComplete = new AutoResetEvent(false);

object nil = new object();
ie.Navigate("", ref nil, ref nil, ref nil, ref nil);

// Waiting for the document to load completely

// Converting the data fetched from the IE instance into HTMLDocument
HTMLDocument theDoc = (HTMLDocument)ie.Document;

// Closing the Internet Explorer Window

// Definition of the function that sets the documentComplete event to true
private void OnIEDocumentComplete(object pDisp, ref object URL)

Unknown said...

The Article on test automation with Internet Explorer is nice .It give detail information about it.Thanks for Sharing the Article about Automation. Software Testing Company

Hugo said...

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Visit here for Penetration testing services