Add Result File with TestContext

This is the last post of the series regarding TestContext. The other posts of this series include:

On Unit Testing:

Usage of TestContext:

In this post, we discuss another member of TestContext called AddResultFile, which is defined as follows.

void AddResultFile(string filename)

Through TestContext.AddResulFile, additional files can be added with the test results. This additional files will be stored in the unique folder created for current test run, as mentioned. This might be useful in some cases, for example, if we are validating our objects with some external resource, like schema— we can store the schema with our test result so that we can validate our test result later on after test run.

Advertisement

TestContext in Data Driven Unit Tests

TestContext consolidates the support of Data Driven Unit Tests via mstest by allowing access to the datasource (e.g., database table), associated with the present code under test. This post describes this very feature of TestContext.

We illustrate this feature with a simple and contrived example (devised only for illustrative purpose), which verify CreateUser API of the application under test. So, we first create a datasource, which is a table that stores contact information.

UserContact Table Definition

After creating a table, we add few users data in the table: UserContact, as shown below.

Data in UserContact Table

Next, we show how TestContext enables us to access row stored in the UserContact table in the following unit test.

[DataSource("System.Data.SqlClient", "[path to MDF]";
Integrated Security=True;User Instance=True", "UserContact",
DataAccessMethod.Sequential), TestMethod()]
public void ShouldCreateUsers(){
string userLoginName = (TestContext.DataRow["LoginName"].ToString());
string userFirstName = (TestContext.DataRow["FirstName"].ToString());
string userLastName = (TestContext.DataRow["LastName"].ToString());
string userEmailAddress = (TestContext.DataRow["EmailAddress"].ToString());
string userDepartment = (TestContext.DataRow["Department"].ToString());
TestContext.WriteLine("Creating user - Login Name :{0} Name : {1} {2} EmailAddress : {3} ", userLoginName, userFirstName,userLastName, userEmailAddress);
bool successful = UserManger.CreateUser(userLoginName, userFirstName, userLastName, userEmailAddress, userDepartment);
Assert.IsTrue(successful);
}
view raw gistfile1.cs hosted with ❤ by GitHub

In this example, we can see that in (line 5 – 10 ), TestContext is providing us access to the current DataRow for which the unit test is getting executed. During execution, we can see the output of TestContext.Writeline(line 12), and the result of the unit test for each DataRow.

To sum up, in this post, we discussed the usage of TestContext in the context of Data Driven Unit Tests. It effectively allows us to access all the DataRows in the test Tables and hence, plays an instrumental role in this context. Thanks.

Related Posts

Other posts of the series are outlined below.

On Unit Testing:

Usage of TestContext:

Unit Testing in ASP.NET Context with TestContext

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.

Page in TestContext

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 FindControl1. Using PrivateObject2, 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);
}
view raw gistfile1.cs hosted with ❤ by GitHub

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:

Performance Measurement with TestContext

TestContext class is equipped with two public methods: BeginTimer and EndTimer, which allow measuring the execution time of an individual unit test. In this way, time required to execute code under test can be measured, and be recorded in reports (e.g., in associated .trx files) as follows.

TestContext.BeginTimer("longRunningProcess");
//.. invoke actual code under test
TestContext.EndTimer("longRunningProcess");

The following screenshot illustrates the report generated from running the above code.

Report Summary

To sum up, we illustrate how to use TestContext to measure execution time of code under test. Check out the next post where we show how to report additional information in test result.

Related Posts

Other posts in this series includes:

On Unit Testing:

Usage of TestContext:

Output additional information in Test Reports with TestContext

TestContext.WriteLine allows additional information to be added in test reports (.trx files) in a flexible manner. This features is particularly useful to report contextual information such as details regarding Test Environments, formal parameters and so on.

[TestMethod]
public void ShouldCreateUser(){
// ... Unit Test Codes....
}

[TestCleanup]
public void TestCleanup(){
    TestContext.WriteLine("{0} : {1}", TestContext.TestName ,TestContext.CurrentTestOutcome);
}

As such, above code-snippet shows the value CurrentTestOutcome after running a test–

Testreport

Hope it helps. Thanks.

Related Posts

Other posts in this series includes:

On Unit Testing:

Usage of TestContext: