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,
MSHTML
Microsoft HTML Object Library
SHDocVw
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)
{
System.Threading.Thread.Sleep(500);
}
mshtml.HTMLDocumentClass doc = ie.Document as mshtml.HTMLDocumentClass;
doc.getElementById("searchbox").setAttribute("value", "test", 0);
doc.getElementById("searchsubmit").click();
while (ie.Busy)
{
System.Threading.Thread.Sleep(500);
}
string bodytext = doc.body.innerHTML;
Debug.Assert( bodytext.IndexOf("documents found")>0);

ie.Quit();

3 comments:

Smridh said...

Also,

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

Code:

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("www.smridh.com", ref nil, ref nil, ref nil, ref nil);

// Waiting for the document to load completely
documentComplete.WaitOne();

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

// Closing the Internet Explorer Window
ie.Quit();


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

Unknown said...

Hello,
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