TestContext is particularly important in the context of ASP.NET web application as it provides an instance of Page
object as TestContext.RequestPage
. It is a reference System.Web.UI.Page
object instantiated for invoking relevant tests, as illustrated below from the debug-context.
Please note that this property is only valid in the context of ASP.NET Unit Testing. Using this instance of Page
object, any control enclosed inside it can be accessed through FindControl
1. Using PrivateObject
2, the private/protected members of the Page
can be invoked.
Following is an example of ASP.NET Unit Test. Note that this example is a simple and contrived one, only for illustrative purpose.
[TestMethod] | |
[HostType("Asp.Net")] | |
[UrlToTest("http://localhost/ourwebapplication")] | |
public void TestMethod(){ | |
Page page = TestContext.RequestedPage; | |
PrivateObject privateObject = new PrivateObject(page); | |
Button button = (Button)page.FindControl("Button1"); | |
privateObject.Invoke("Button1_Click", button, EventArgs.Empty); | |
Label label = (Label)page.FindControl("Label1"); | |
Assert.AreEqual<string>("Hello World !!!!", label.Text); | |
} |
It is worth noticing that we are using IIS to host ourwebapplication
(shown in Line 3). What it essentially does is test whether button-click event it working as excepted: We have a Label
and a Button
in a web page. When this button is clicked, the Label.Text
is changed to "Hello World!!!"
.
Therefore, we can see that by leveraging TestContext
, we can essentially write and execute unit and integration tests for any ASP.NET web page, and thus, can increase code coverage and enhance static verification of the whole application. In the next post, we discuss now we can use it in the context of Data Driven Unit Tests.
We hope that this discussion helps in devising more effective unit tests. We highly appreciate any comments or queries regarding this post. Thanks!
Related Posts
Other posts of the series are outlined below.
On Unit Testing:
Usage of TestContext: