WatiN & NUnit

How to use WatiN with NUnit in a C# environment with Asp.NET MVC

WatiN Framework

I was asked to write web tests for a suite of web applications. We already had a good coverage (about 65 %) with lots of unit tests on the controllers and models of our applications but it was hard to test the views.

Lots of functionalities are coded in HTML, CSS and Javascript and are not testable directly using back-end code. They require a specific runtime environment: the browser. The browser that reads the HTML and CSS, and runs the JavaScript.

WatiN (pronounced as What-in) is a framework that lets you run a browser and directly send intructions to it. You can visit pages, click different links and test content.

NUnit Framework

NUnit is a library in .Net to write and easily maintain unit tests in C#. If you use combine the use of WatiN and NUnit, you can write unit tests for you web application.

Extend WatiN to CSS selector with jQuery

WatiN is great, but you cannot use CSS selector (cf. above example on how to find an element). in JavaScript frameworks (like jQuery), you can use CSS selectors to get an element. WatiN allows you to inject JavaScript in the browser.

So you can inject a CSS search monitor which will perform the search using jQuery, check if the element has an id attribute, set one if not and return this id. Then WatiN uses this id to get the element.

And then on the WatiN side, you inject the JavaScript and you call CssSearchMonitor.getElementId in order to get an element id.

stringjavascript=getJavaScript();// Get the javascript of the css search monitor.using(varbrowser=newIE("http://www.google.com")){browser.Eval(javascript);stringid=browser.Eval("CssSearchMonitor.getElementId('div.myClass input[input=\"button\"]', 1)");Buttonbutton=browser.Button(id);button.Click();}

In order to use it intensively, you still need to refactor it to make it easy to use, but the main idea is here. Happy testing with WatiN and NUnit.

But there is still an open problem, how do you measure the coverage of the web application ?