Getting Directory of Current Context with TestContext

The current test run creates a unique directory for running tests and storing the generated reports (.trx) files.

TRX files

In effect, additional inputs and outputs (especially, in case of data driven unit tests) can be persisted in these unique directories during test runs. In addition, unit testing process has complete access in these directories. So, it would be consistent while running the tests in any machines (e.g., in build machines or in local development environments).

Using TestContext, we can get the path of the directory related to the current test run as follows.

string testDirectory = TestContext.TestDir;

We can get the deployment directory and the directory that contains logs as follows.

string deploymentDirectory = TestContext.TestDeploymentDir;
string logDirectory = TestContext.TestLogsDir;

To sum up, this post has described how we can get/set several important properties from TestContext. In the next post, we show how we can use it for performance measurement.

Related Posts

Other posts in this series includes:

On Unit Testing:

Usage of TestContext:

More on Unit Testing: TestContext

From empirical evidence, we know that improving code coverage by verifying all the boundary conditions, and ensuring quality of code-base significantly enhances maintainability and comprehensibility of complex software systems. Therefore, writing effective unit and integration tests has become one of the integral part in software development life cycle. In fact, development methodology such as TDD has been embraced rapidly due to these realized benefits.

In today’s post, we talk more about TestContext of mstest. In particular, we focus on its usage in devising effective unit tests. Before moving forward, we would like to outline the previous posts of the series regarding Unit Testing.

What is TestContext?

TestContext is an abstract class of Microsoft.VisualStudio.TestTools.UnitTesting namespace. It exposed several properties related to the current context (i.e., current test run). In addition, it provides following supports:

  • Get/set context-sensitive properties and instances, For instance,
    • During unit tests, it stores server’s URL, and Page object.
    • For data driven unit tests, it provides access to the data rows.
  • Mechanism to measure performance of unit tests.

Following is the class definition of the TestContext class.

How can we initialize TestContext?

To start using TestContext, we need to add a property in our unit test class, e.g., UserManagerTests, as illustrated below.

UnitTest class with a TestContext

As we run a unit test defined in UserManagerTests, we automatically get an instance of TestContext with the relevant properties configured according to the current context. Thus, we do not require to explicitly instantiate it. Using debug mode, we can verify that the instance of TestContext is an instance of UnitTestAdapterContext, which is, in fact, derived from TestContext abstract class.


In addition, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter.dll assembly contains UnitTestAdapterContext class, which is located in the directory of private assemblies installed in <vs installation directory>\common7\IDE\PrivateAssemblies.

Note that the property TestContext is actually initialized after ClassInitialize and before TestInitialize gets invoked.

In this post, we discuss how we can initialize TestContext in a test class. As a continuation of this discussion, we outline several use-cases of TestContext in the following posts.


To sum up, in this series, we introduce TestContext and has discussed how we can utilize it in different scenarios to write effective unit and integration tests. We hope that it would help to devise more effective and maintainable unit tests. Lastly, we emphasize on designing test cases thoroughly, and mapping them essentially into unit and integration tests accordingly, because only "harnessing the power that is provided by the tool and utilizing it effectively and every possible way" could bring desirable result. We highly appreciate any comments or any suggestion regarding this series. Thanks.


[R-1: 04-04-2013] Porting this blog-post from its page.

Designing Efficient Immutable .Net Objects

What is an immutable object?

By definition immutable object is the object whose state can not be changed after it is created. That means, after creating the object, its publicly exposed members can not be changed from their initial assigned values. On the contrary, mutable objects are objects whose state can be changed at any point of time.

Every developer has to take a important decision whether to make a class mutable or immutable while designing the domain model.
While taking this decision, careful considerations can make us avoid the potential pitfall of using immutable object. 
 Why & How using immutable .Net object – is our today’s discussion. Let’s begin with How part . 

How to implement .Net Immutable Object?

 The way I would implement an immutable .Net class –           

          Make the fields private readonly.
          Provide a Public property with get accessor.
          If the class is no longer needed to inherited – making it sealed. 

Like in the following example, I am implementing an immutable class  UserContact which will be inherited in User  


 Here is the Implementation of the Immutable classes –     

    public class UserContact


        private readonly string _Name;

        public string Name   


            get { return _Name; }


        private readonly string _EmailAddress;

        public string EmailAddress


            get { return _EmailAddress; }


        public UserContact( string name , string emailAddress)


            _EmailAddress = emailAddress;

            _Name = name;



UserContact get inherited by User as follows [Since User class is no longer inherited – we make it sealed] –

    public sealed class User : UserContact


        private readonly string _UserName;

        public string UserName


            get { return _UserName; }


        public User(string name, string email, string userName)

            : base(name, email) { }


So, isn’t it really easy to implement a Truly Immutable class in .Net framework? J Now the question pops into our mind – why we will be using immutable .net objects , what would be benefits of that ? Let’s explore that –  

Why use immutable object?


From the definition we know, Immutable objects can not be changed after its being initialized. So, while using inside application, immutable object can flow in different layers of the application without getting worried about being altered by different layers.  


Copying object will be much easier, we just need to copy the reference instead of copying the whole object. It would be much faster to copy reference than the whole object.

User user = new User(“adil”, “”, “adak”);
User userTemp = user; 

In case of mutable object, we would need to create defensive copy of the object and in .Net term, we need to create a Deep Copy of object otherwise, changing a property in the actual mutable object would reflect everywhere where the object is referenced. For example, let’s consider User as mutable; then changing any thing in user object will have same impact on userTemp as well which is not intended.

To avoid this situation, in case of mutable object, we need to make a Deep Copy of the object which is a costly operation. However, for immutable object, copying the reference would be enough since its state can’t be changed. 


Thread synchronization is an issue of concern while designing multithreaded application. Overhead of synchronizing immutable object is far less than mutable object. By default , an individual immutable object does not need to be synchronized as its state will be not be modified by any thread. However, since the immutable object will still be accessed thorough reference , it would require some synchronization. In complex sync scenarios, immutable object would perform far better then mutable version.   


If we consider inheritance hierarchy, immutability provides a way for the sub-class to maintain consistency in inheritance hierarchy. Consider following mutable objects–


When we instantiate the StudentMutable object, the AccountType is automatically set to Student Account –

public StudentMutable(string name , string email , string userName )
: base(name ,email , userName,“Student Account”){}

 Now, we can write following lines by which the AccountType property could be anything other than “Student Account” which is completely inconsistent –   

StudentMutable mutable = new StudentMutable(“Adil”, “”, “adil”);   
mutable.AccountType = “whatever account”;   

But if we use Immutable object in inheritance – the object hierarchy will always be consistent.:) 

What to consider while designing Immutable objects?

Intantiation of immutable object might be considered an operation that will be done more frequently. Then the allocation and freeing the resource for the immutable object would be the most recurrent opertaion which might result as performace overhead. Incase of regular objects , it seems that syncronization is far more costly operation from CPU perspective than allocating and freeing resource.  

For objects that require significant time to initialize , we may consider to implement Object Pool or Flyweight pattern to enhance reusability.  


 So , We can achive much faster and efficient code if we use Immutable object. But by saying all this , definitly we need to design accordingly and carefully so that immutable object can perform to its best. In this article , we learn how to implement immutable object in .Net and what’s its benefits and what we need to consider while implementing immutable object. In my next post , I am thinking to write something about reusing the immutable object to enhance efficiency. Thanks for visiting the the blog. Let me know your comments and feedbacks. Bye J 

Inside .Net Constants

By definition, constants are fixed numbers or values which represent the universal facts. When comes to programming language, it represents the same analogy- symbol with “Never-Changing Value”. In .Net Framework, constant(const) represent a symbol which contain a fixed/never changing value. Defining a constant in C# – 

           public const string Bullet = “\u2022”; 

We can use any primitive types supported in .Net Framework to define constant.   When we define a constant, the symbol is stored in the module’s metadata in compile time and compiler gets its value and copies it to the emitted IL code generated. In short, const value is directly embedded inside the code.           

Some facts about .Net const:

1.       Value of the const is decided in compile time. 
2.       We can only define const for primitive type.
3.       const are saved in the module’s metadata which then extracted and emitted in the IL code generated during compile time.
4.       Since there is no memory address is allocated for the constant – we can’t pass a const by reference. Therefore, it does not have good cross-module versioning usability. I will come back to this point.
5.       const symbol’s value never changes. That’s why, const symbols are associated with the .Net Type rather than instances.

Design consideration while using const: 

const should only be used when it is known that it’s value will never change, as I mentioned in the definition– universal fact. J For example – I defined here a const that represented the Unicode of the Character Bullet which kind of an Universal fact and will never change. Now, if we define const symbol that changes [I think which needs a code reviewJ], the problem that we might face is Cross-Module versioning. Let’s check out the following code which resides in a .dll –   public class ConnectionStrings
public const string UserDbConnectionString = “…”;

And we are using
ConnectionStrings class by adding reference of the .dll in our application. As we already know, the const symbol’s value  just emitted in the IL code and UserDbConnectionString const actually don’t need any Memory allocation, which makes the .dll file not being loaded at runtime. The value of UserDbConnectionString is already copied from the module’s metadata to our application’s generated IL. We can simply delete the .dll file and it should work accordingly.

There is no problem in so far. However, due to some reason, the value of the UserDbConnectionString get changed [ May be due to the deployment issue.]. Now we build the dll. How come the change is not reflected in our application’s code ? J Dude, we need to re-build our application as well. L 

To state the whole Versioning things in short – we need to keep into consideration while we define a constant symbol in our module whether the symbol will be referenced across the module. If the const symbol does not need any cross-module reference – then we should go for const otherwise, we need to change the implementation, For the above mentioned example I would change the const to readonly –   public class ConnectionStrings
      public readonly string UserDbConnectionString = “…”;

Lunch breakJ. I will try to post on readonly later on.