Watin: test web applications in. net

Source: Internet
Author: User

This article Reprinted from: http://www.testage.net/html/57/n-957.html

Introduction

Unit testing is an important part of application design. It can be applied to multiple layers of programs. This article focuses on unit testing at the user interface layer. We will use watin to test ASP. NET applications.

What is watin?

Watin is a tool derived from watir used to test web pages. WatinWEBAPplicationTEstingIN.NET.

What should we test?

In this article, we will test a simple ASP. NET page, which will be used to demonstrate the scenario of identity and acceptance (agreement acceptance. Enter a name in the text box, click the "I agree" check box, and then press the submit button. This is obviously a very simple page. After you are familiar with the working mechanism of the watin framework, you can use this idea for testing large pages.

Here is the page to be tested:

Agreement page:

Add a class library project to the solution and add the test tool to it (I use mbunit here, but you can use nunit or vsts test project) and the reference of the watin library. You can download watin here.

The following test code is used to ensure that the user has accepted the code.

[TestFixture(ApartmentState = ApartmentState.STA)]
public class TestAgreementPage
{
    [Test]
    public void TestCanAcceptUserAgreement()
    {
        IE ie = new IE(ConfigurationManager.AppSettings["DefaultPageUrl"]);
        ie.TextField("txtName").TypeText("Mohammad Azam");
        ie.CheckBox("chkAgree").Checked = true;
        ie.Button("btnAgree").Click();
 
        Assert.AreEqual("Valid", ie.Span("lblMessage").Text);
    }
}

 

This class has the testfixture feature (attribute). The STA value ensures that the test runs in the sta (single threaded apartment) state. This is because the test code needs to load IE.

The IE class in watin completes the main work. Open the IE class and reference the HTML control by name or ID. This line of IE. textfield ("txtname"). typetext ("Hammad Azam") references the text box with ID "txtname. After the browser loads the file, watin writes the value "Hammad Azam" to the text box with the ID "txtname. You will see this process during testing. The check box with the ID of "chkagree" is selected. Finally, watin presses the submit button to submit the form.

Failed to run the test. Because the label named "lblmessage" is never assigned "valid ". Add this Code:

protected void btnAgree_Click(object sender, EventArgs e)
{
    lblMessage.Text = "Valid";
}

Now, if you run the test, it will pass. However, it seems incorrect. If we delete this line of test code:

ie.CheckBox("chkAgree").Checked = true;

Run the test again and pass the test again. This is wrong! It should be passed only when the checkbox is selected. Modify the code behind of the page.

protected void btnAgree_Click(object sender, EventArgs e)
{
    if (chkAgree.Checked)
    {
        lblMessage.Text = "Valid";
    }
}

 

Now, the test can pass only when the checkbox is selected.

Run the Web server programmatically:

In the above example, we need to run webserver either through the command line tool or by running the WEB Project. However, sometimes we need a unit test project to dynamically open a webserver. Let's take a look.

First, if you need to open the ASP. NET internal server (webdev. webserver), you can use the command line. Syntax:

Webdev.webserver.exe/port: 1950/path: "C:/projects/mywebapplication"

You need to locate the directory where webdev. WebServer is located. By default, it is in:

C:/Windows/Microsoft. NET/framework/v2.0.50727/webdev.webserver.exe

Now let's take a look at how to open the server in unit test. First, add necessary configurations (in APP. config ).

<configuration>
    <appSettings>
        <add key="WebServerExePath" value="C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/WebDev.WebServer.exe"/>
        <add key="Port" value="4463"/>
        <add key="WebApplicationPath" value="c:/projects/demowatiN/demowatiN" />
        <add key="DefaultPageUrl" value="http://localhost:4463/Default.aspx" />
    </appSettings>
</configuration>

 

The basetestpage class can run the server through this information. All the test classes that inherit it can use this function.

The complete code of the basetestpage class is as follows:

public class BaseTestPage
{
    static Process server = null;
 
    static BaseTestPage()
    {
        if (Process.GetProcessesByName("WebDev.WebServer").Length == 0)
        {
            string webServerExePath = (string)ConfigurationManager.AppSettings["WebServerExePath"];
            server = new Process();
            Process.Start(webServerExePath, GetWebServerArguments());
        }
    }
 
    public static string GetWebServerArguments()
    {
        string args = String.Format("/port:{0} /path:/"{1}/"", GetPort(), GetWebApplicationPath());
        if (String.IsNullOrEmpty(args)) throw new ArgumentNullException("Arguments is not defined");
        return args;
    }
 
    public static string GetPort()
    {
        string port = ConfigurationManager.AppSettings["Port"] as String;
        if (String.IsNullOrEmpty(port)) throw new ArgumentNullException("Port is null or empty");
 
        return port;
    }
 
    public static string GetWebApplicationPath()
    {
        string webApplicationPath = ConfigurationManager.AppSettings["WebApplicationPath"] as String;
        if (String.IsNullOrEmpty(webApplicationPath)) throw new ArgumentNullException("WebApplicationPath is null or empty");
 
        return webApplicationPath;
    }
}

If the server is not running, a new process is created to run it. Otherwise, an existing process is used.Getwebserverarguments(),Getport() AndGetwebapplicationpath() Is only an auxiliary method that can improve readability.

Finally, you can let the unit test class inherit the class:

Public class testagreementpage: basetestpage

Now, when you run a unit test project, it runs webserver and then executes all tests.

Conclusion:

In this article, we learned how to perform unit tests on the user interface layer. These tests help us understand the UI requirements and quickly see the results obtained based on user input. However, manual testing takes a lot of time.

Source code: click here.

Author: Anders Cui
Source: http://anderslly.cnblogs.com
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.