Detect when a unit test is running

When working with unit tests there are many objects that cannot be unit tested. A prime example is the Request and Response objects. They both contains a lot of HTTP data that can only be accessed when running a web application.


You can implement what is known as mocking, using a 3rd party framework such as Moq you can configure these objects with very specific data such as the URL, Cookie and Session data.
A very effective and simple way to overcome this issue is to detect in code when its being accessed by a unit test and update the logic as necessary. See the example below which handles a http session UserID object.

 

public class GlobalHelperMethods
{
	/// <summary> 
	/// Detects if the current code is being executed from a unit test. 
	/// </summary> 
	/// <returns></returns> 
	public static bool Detect_IsUnitTestRunningLogic()
	{
		string testAssemblyName = "Microsoft.VisualStudio.QualityTools.UnitTestFramework";
		return AppDomain.CurrentDomain.GetAssemblies()
		.Any(a => a.FullName.StartsWith(testAssemblyName));
	}
}

This can be use like so...

int UserID = 0;

// get the userID from the Session
if (!GlobalHelperMethods.Detect_IsUnitTestRunningLogic())
{
	UserID = _UnitTestUserIDVal;
}
else
{
	// Get the UserID from the Session
	if (Session["UserID"] != null)
	{
		UserID = Convert.ToInt32(Session["UserID"]);
	}
}

// continue logic...

Hacky? Yes but very simple and effective.


JGilmartin Profile Image

JGilmartin

Technical Architect at Pinewood Technologies

Rating: 2890

C# Expert

Offline


Useful Tip Statistics
  • Views: 748
  • Comments: 0
  • Author: JGilmartin (2890)
  • Date: 8/12/2016 18:29
Tags
C# .NET

© 2016 - 2018 - IntermittentBug