Coalesce data functionally

In a recent project I had to coalesce quite significant amount of data in the following way. To simplify it for this post, consider that we have the following two lists.

val x = List(“a”, “b”, “c”, “a”)

val y = List(1, 2, 6, 9)

We are about to write a function which would return the following list as the result.

val result = List((a,10), (b,2), (c,6))

Basically it would coalesce value with the same category. See for instance “b” in the above example.

Language that came up with repl inherently provides very nice way to try out different expression and to get to the expected outcome. In this context, as we are using scala, we can use repl-driven development quite conveniently as illustrated below.

  • Define the Lists:
scala> val x = List("a", "b" , "c", "a")
x: List[String] = List(a, b, c, a)

scala> val y = List(1,2,6,9)
y: List[Int] = List(1, 2, 6, 9)
  • Zip them.
scala> val z = x zip y
z: List[(String, Int)] = List((a,1), (b,2), (c,6), (a,9))
  • Group them based on the values of x.
scala> val grps = z groupBy (_._1)
grps: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(b -> List((b,2)), a -> List((a,1), (a,9)), c -> List((c,6)))

  • Map the values of res8 and reduce them to compute the sum.
scala> val res = {_.reduce((i,j) => (i._1, (i._2+j._2)))}

res: Iterable[(String, Int)] = List((b,2), (a,10), (c,6))
  • Sort res based on the 1st value of the tuple.
scala> res.toList.sorted
res23: List[(String, Int)] = List((a,10), (b,2), (c,6))


Thus, the function can be simply written as follows:

def coalesce(x:List[String], y:List[Int]):List[(String, Int)] =
(x zip y).groupBy(_._1)
.map{_.reduce((i,j) => (i._1, (i._2 + j._2)))}
view raw coalesce.scala hosted with ❤ by GitHub

Thus we get the expected result.

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);
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.

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.

//.. invoke actual code under test

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.

public void ShouldCreateUser(){
// ... Unit Test Codes....

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

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


Hope it helps. Thanks.

Related Posts

Other posts in this series includes:

On Unit Testing:

Usage of TestContext: