In these days if we cover most of our code with tests we can guarantee our code works. If ours tests are working well it says a very important thing, we are delivering a good build and the future changes will be costless! To accomplish this scenario I study some tools to improve my test cover and I will share them with you.
WatiN
Let's start by WatiN (pronounced as What-in), it provides a way to automate tests using IE or Firefox using .NET.
Creating a Simple Project
Now we will use WatiN in a simple example. Use the following next procedure and fun!
- Create an empty Web MVC project
- Create a new controller (I named it WatinController)
Add the 2 actions “Page1” and “Page2” (right-click action and select “Add View”).
- Create a Page2 view (like a page1), but with the title page2.
- Run your project and see if everything is right!
Creating a test project
Here we will use WatiN to test our application.
Create a UnitTestProjectInstalling WatiN
First we need to install WatiN in our project test.
- In Nugget type “watin”, and install it as in the following:
- Go to references and find Interop.SHDocVw and change the property “Embed Interop Types” to false:
Testing
Now we use watin to load our index page and check if the “title” is correct. We can do this like this:
- [TestMethod]
- public void TestIndex()
- {
-
- IE browser = new IE("http://localhost/WatinSpecflowSample/Watin");
-
-
- string title = browser.ElementWithTag("h2", Find.ById("title"), null).Text;
-
-
- Assert.AreEqual(title, "Index");
-
-
- browser.Close();
- }
If we run this test you will see the browser opening and closing. And checking the result of test is passed. \o/
Let's put some difficulty in our tests. Create a new Test Method named by “TestClickPage1”, and try this:
- [TestMethod]
- public void TestClickPage1()
- {
-
- IE browser = new IE("http://localhost/WatinSpecflowSample/Watin");
-
-
- browser.Link("page1").Click();
-
-
- browser.WaitForComplete();
-
-
- string title = browser.ElementWithTag("h2", Find.ById("title"), null).Text;
-
-
- Assert.AreEqual(title, "Page1");
-
-
- browser.Close();
- }
Running it you will see the result.
Doing the same for the Page3 link, the test will fail and this shows how important it is to cover our application with tests. We can anticipate this error and fix it before generating a build. I know, writing tests seems boring, but if we do this in the begining of the project then this eventually becomes normal. The purpose of this article is just to show how to use WatiN to test our UI web application.
In the next article I will integrate Specflow and WatiN to create a more understandable test.