I sort of hate answers that say "don't do that" because there might be value in the answer, regardless of the approach, however, here we go:
Don't do that.
Let's assume you have this class:
public class MyCode
{
public void Do()
{
HttpContext.Current.Trace.WriteLine("WOO!");
}
}
This kind of thing isn't very testable. If you wanted to refactor for testability, you could use more of an "inversion of control" type of method. Here I'll use "dependency injection" (there are other options, like "service location" and "abstract factories", but this is easiest to understand):
public class MyCode
{
private IMyLogger _logger = null;
public MyCode(IMyLogger logger)
{
_logger = logger;
}
public void Do()
{
_logger.TraceWriteLine("WOO!");
}
}
Now you can see that this code is very testable and you don't have to jump through hoops to mock anything.
//Confirms "Do" method calls "TraceWriteLine"
public void Do_Called_CallsTraceWriteLine()
{
//Arrange
var loggerMock = new Mock<IMyLogger>();
loggerMock.Setup(l => l.TraceWriteLine(It.IsAny<string.());
var target = new MyCode(loggerMock.Object);
//Act
target.Do();
//Assert
loggerMock.VerifyAll();
}
Now your implementation of IMyLogger might call out to HttpContext, but it keeps your target class testable.
public DefaultLogger : IMyLogger
{
public void TraceWriteLine(string message)
{
HttpContext.Current.Trace.WriteLine(message);
}
}
To implement such a thing, many people choose to use an Inversion of Control container. You don't have to do this, but it makes things a little simpler and doesn't decrease maintainability as you add more dependencies. You can imagine if you had an interface for each part of the .NET framework that was untestable, your "new MyCode" constructor calls would start to get quite long. IoC containers help you avoid this.
Popular IoC containers for .NET:
- Ninject
- Unity
- MEF (builtin to .NET 4.0)
- Autofac
- Castle Windsor
- StructureMap
Your post is tagged "ASP.NET". Hopefully you are using MVC. If so, it has new support for dependency injection, examples here:
http://weblogs.asp.net/shijuvarghese/archive/2011/01/21/dependency-injection-in-asp-net-mvc-3-using-dependencyresolver-and-controlleractivator.aspx
Hopefully this helps. Sorry it doesn't directly answer your question.